java - 模拟在同一个类中调用的方法的响应
问题描述
我正在尝试为以下类场景编写 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
}
}
上述类的 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 测试用例时,由于返回的详细信息值为 null,因此抛出 NullPointerException。解决上述错误的更好方法是什么。TIA。
--EDIT-- 在上面的代码示例中,为了更清晰,添加了 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 类以将 @Autowired 注入替换为构造函数注入。
(对于 getTheMockResponse() 它是您测试类中的私有方法?)
推荐阅读
- python - 如何使用 python 通过子值从 YAML 文件中获取父 ID?
- c# - 以编程方式将父 ViewModel 的命令添加到按钮
- python - 如何使用 tf.data.Dataset.from_tensor_slices 和 map 加载 np.array
- django - 将 websockets 集成到 Django Rest Framework 应用程序的简单方法?
- akka - 测试 AKKA 2.6 持久性演员类型(Kill 和 PoisonPill 的替代品)
- sql - 如何解析以下 JSON 字段?(PostgreSQL)
- c# - Google drive api v3 在同一请求中创建多个副本以在 C# 中驱动服务
- python-3.x - 循环内的 Python PyQt5 组合框连接
- python-c-api - 如何正确地将 CuPy 数组发送到 Python C 扩展模块
- stripe-payments - 具有不同持续时间的产品的条带订阅