I am trying to stub method of testing class. And it is not working.
Like am testing below class
enter code here
Class to test:
public Class A{
public String method1(){
C c=new C();
int num=c.methodC();
B b=new B();
String str=method2(b);
return str;
}
public String method2(B b){
String str=method2(b);
return str;
}
}
JUnit class:
#RunWith(JUnitPlatform.class)
Class ATest {
#InjectMocks
A a;
#Mock
C c;
#Mock
A a1;
#BeforeEach
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testMethod1(){
Mockito.doReturn(34).when(c).methodC(anyString());
a1=Mockito.mock(A.class);
Mockito.doReturn("Added successfully").when(a1).method2(any(B.class));
assertEquals("Added successfully", a.method1());
}
}
When am stubbing methodC(...) from Class C it is working. But method2(...) from Class A is not stubbing.
Please let me know what is the issue, and solution.
You have 2 options to mocka parts of the object.
Option 1: use a #Spy instead of a #Mock
#ExtendWith(MockitoExtension.class)
class ATest {
#Spy
A a;
#Test
public void testMethod1() {
Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
assertEquals("Added successfully", a.method1());
}
}
Option 2: Use a mock and mark real implementations
#ExtendWith(MockitoExtension.class)
class ATest {
#Mock
A a;
#Test
public void testMethod1() {
Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
Mockito.doCallRealMethod().when(a).method1();
assertEquals("Added successfully", a.method1());
}
}
I found via trial and error method that, methods in testing class cannot be mocked. In case we have to mock a method, either we have to move such methods to different class, or do not mock it. That is the only solution.
Related
How to stub a System.currentTimeMillis() in the classB from classA?
Class A:
public classA {
#Test public void timeTest() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(10L);
B.testPowerMock(); }
}
Class B:
public class B {
public static void testPowerMock() {
System.out.println(System.currentTimeMillis());
}
}
When I am testing a class A (TestNG) which uses some methods from some other class Helper Class
I am mocking the helper class(Mockito) for testing class A.
but when(helper.methodUsedByClassA(value)).thenReturn(new HashMap>())
this line of code is actually calling helper.methodUsedByClassA and a null pointer exception is thrown (because of data I am using for testing is not valid)
why is this happening? Why would the method name inside mockito "when" actually be called ?
class ATest{
#Mock
private Helper helper;
private A target;
#BeforeTest
public void setUp() {
MockitoAnnotations.initMocks(this);
this.target = new UpdateDigicatKdpAsinUtil(helper);
}
#Test(dataProvider = "data")
public void testMethod(List<String> value) {
when(helper.methodUsedByClassA(value)).thenReturn(new HashMap<String, List<String>>({{put("test", new ArrayList<>())}}));
}
#DataProvider
public Object[][] data(){
List<String> list = new ArrayList<>();
return new Object[][]
{
{list}
}
}
class Helper{
public Map<String, List<String>> methoUsedByClassA(int value) {
//This method is being executed because it is mentioned inside "when"
}
}
I guess you get an NPE because helper is NULL.
The problem is that the #Mock annotation isn't processed and because of that, the variable helper isn't initialized.
You have to annotate the test class with #RunWith(MockitoJUnitRunner.class). MockitoJUnitRunner will process the #Mock annotation and create the mock.
Below is my code snippet. This is giving me compilation error, as env.getProperty will return String. How do I get integer value. Interger.ParseInt is not working.
when(this.env.getProperty("NeededIntegerValue")).thenReturn(15);
Below is my test class
public class MyclassTest {
Myclass myObj=new Myclass();
#Mock Environment env=Mockito.mock(Environment.class);
#Before
public void init() {
when(this.env.getProperty("StringKey1")).thenReturn("Stringvalue");
when(this.env.getProperty("StringKey2")).thenReturn(intValue);
myObj.setEnvironment(this.env);
}
#Test
public void testTenantIdentifierCutomerTypeCUSTOMER_ACCOUNT() {
assertEquals("Expecteddata",myObj.testMethod(new StringBuilder(inputData),anotherData).toString);
}
}
Below is the Method needs to be tested
public StringBuilder testMethod(StringBuilder inputData, String anotherData)
{
if (anotherData.equals(env.getProperty("StringKey1"))) {
inputData=inputData.append(","+arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))]);
}
}
First, you should mock your env, this way:
when(this.env.getProperty("StringKey1")).thenReturn("StringValue");
when(this.env.getProperty("StringKey2")).thenReturn("StringRepresentationOfYourInt");
Second, pay attention to the method itself, should be
arrayOfInputData[Integer.parseInt(env.getProperty("StringKey2"))
not
arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))
Instead of
myObj.setEnvironment(this.env); in init() method try:
#InjectMocks
Myclass myObj = new Myclass();
Also remove assignment for
#Mock Environment env=Mockito.mock(Environment.class);
it should look
#Mock Environment env;
I use PowerMockito mock a class instance that contains private method. And I want to verify private method return value is correct, So how to use PowerMock invoke private method and get return value?
This is demo:
class Demo {
public publicMethod1ReturnClass publicMethod1() {
// do something...
}
private privateMethod1ReturnClass privateMethod1() {
// do something
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(Demo.class)
class DemoTest {
#Test
public void test() throws Exception {
Demo demo = PowerMockito.spy(new Demo());
privateMethod1ReturnClass result = demo.privateMethod1();
}
}
You can do it using Whitebox like this,
privateMethod1ReturnClass s = Whitebox.invokeMethod(demo, "privateMethod1");
assertEquals(s, "yourExpectedResult");
Not duplicate of: Inherited test class from generic base is ignored in MSTest
In my case, the test classes are in the same namespace/assembly.
When unittesting classes which have a lot in common, I would like to use a base test class with a generic parameter. I have boiled the problem down to the following, where my base test method is not being executed, but ONLY in the generic case.
Non-generic: Base test method is EXECUTED:
[TestClass]
public class DerivedTestClass : BaseUnitTest
{
protected override string ReturnMeSomething(object obj)
{
return "test1" + obj.ToString();
}
[TestMethod]
public void derived_test()
{
// This is executed
}
}
[TestClass]
public abstract class BaseUnitTest
{
[TestMethod]
public void base_test()
{
// This is executed
}
protected abstract string ReturnMeSomething(object obj);
}
Generic: Base test method in generic base class is NOT EXECUTED:
[TestClass]
public class DerivedTestClass : BaseUnitTest<string>
{
protected override string ReturnMeSomething(string s)
{
return "test1" + s;
}
[TestMethod]
public void derived_test()
{
// This is executed
}
}
[TestClass]
public abstract class BaseUnitTest<T>
{
[TestMethod]
public void base_test()
{
// This is NOT executed
}
protected abstract string ReturnMeSomething(T t);
}
Can anyone tell me the reason for this?
After a few days, this suddenly works (!!). If anyone ever experiences this same, odd behavior, please write a comment here. I would suggest anyone to reboot and clean+rebuild everything and try again.