模拟在同一个 class 中调用的方法的响应

mocking the response for the method called inside the same class

我正在尝试为以下 class 场景编写 JUnit 测试用例。

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
}
}

上述 class.

的 JUnit
@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");
}
}

当执行上述 JUnit 测试用例时,它抛出 NullPointerException,因为返回的详细信息值为 null。解决上述问题的更好方法是什么 error.TIA.

--编辑-- 在上面的代码示例中,添加了 class3 依赖逻辑以便更清晰。

在这种情况下试试这个代码

@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");
}
}

不要忘记更改您的 Class1 class 以将 @Autowired 注入替换为构造函数注入。

(对于 getTheMockResponse() 它是您测试中的私有方法 class?)