junit - 无法在java中的方法内模拟局部变量
问题描述
我是测试新手,使用 mockito 和 junit 进行测试。类和测试方法看起来像这样。编辑:对方法进行了更正。
class SomeClass
{
Data data;
public Data method1(int n1, int n2)
{
data = method2(n1, n2);
if (data != null && data.something()!=null && !data.something().isEmpty())
{
// other instructions
}
return data;
}
Data method2(int n1, int n2)
{
Data data1 = Some calculations;
return data;
}
}
//Test class
@Mock
Data data;
@Test
public void testData()
{
@Test
public void getReceivingDataTest()
{
SomeClass mock = Mockito.spy(new SomeClass.class);
when(mock.method2(1,1)).thenReturn(data);
mock.method1(1,1);
}
}
在这里,我试图从测试方法中设置从 method2 接收到的数据的值,但不幸的是我无法模拟局部变量Data data。它调用真正的方法method2并获得一个空值并抛出一个空异常。我曾尝试使用模拟而不是间谍,但我得到了同样的错误。我该怎么办?编辑:method2() 正在调用另一个服务,因为我模拟了它,所以总是返回 null,并且不会执行 method1() 中的“其他指令”。
解决方案
推荐阅读
- c - C 中的内存管理 - Linux 内核
- php - 在 php 中使用 for each 迭代 mysql 查询
- r - 将一个 sf 对象导出到多个 shapefile
- ios - 如何将自定义脚本传递给 ./configure 以在编译后运行?
- android - 如何从表 SQLite 中获取最后一条记录
- php - 更新了 composer.json 中的 symfony,但在尝试使用“require”安装新软件包时出现错误
- node.js - Axios - 请求失败,状态码 400 错误
- r - 将时间列更改为没有日期值的 POSIXct
- android - getView() 方法中的 Parent 到底是什么
- delphi - Delphi 源代码仅具有 LF 与 CRLF 导致 IDE 中的源损坏