mocking the response for the method called inside the same class

Tags: , ,



Iam trying to write JUnit test case for the below class scenario.

public class Class1{

@Autowired
Class2 class2Obj;

@Autowired
Class3 class3Obj;

public MyResponse searchTheDetails(String id){
GetDetails details;
List<String> names;
id(id!=null){
 details = getDetails(id); //while running JUnit ,**details** value is null always and throwing NPE at next line.
 names = searchByNames(details);
}
return filterName(names);
}

public GetDetails getDetails(String id){
//logic
int i = class3.load().countOccurence(id);//we are using class3 object here
return class2Obj.getData(id,i);//this line was mocked in the below jUnit
}
}

JUnit for the above class.

@SpringBootTest
class Class1Test{

@InjectMocks
Class1 class1;
@InjectMocks
Class3 class3;
@Mock  
Class2 class2;
MyResponse myResponse;

@BeforeEach
void setUp(){
MockitoAnnotations.initMocks(this);
class3 = class3.load();
myResponse = getTheMockResponse();
}

@Test
void test(){
Mockito.doReturn(myResponse).when(class2).getData(Mockito.anyString(),Mocito.anyInt());
MyResponse resp = class1.searchTheDetails("21233");
}
}

When the above JUnit test case is executed, it is throwing NullPointerException as the details value returned is null. What is the better approach to solve the above error.TIA.

–EDIT– In the above code sample, added the class3 dependency logic for better clarity.

Answer

In this case try this code

@SpringBootTest
class Class1Test{

@InjectMocks
Class1 class1;
@Mock
Class3 class3;
@Mock  
Class2 class2;
MyResponse myResponse;

@BeforeEach
void setUp(){
this.class1 = new Class1(class1, class3); 
myResponse = getTheMockResponse();
Mockito.when(class2.getData(Mockito.anyString(),Mocito.anyInt())).thenReturn(myResponse);

}

@Test
void test(){
MyResponse resp = class1.searchTheDetails("21233");
}
}

Dont forget to change your Class1 class to replace @Autowired injection with constructor injection.

(For the getTheMockResponse() it’s a private method in you test class? )



Source: stackoverflow