java - 模拟类返回 null 而不是数据
问题描述
在我的 Junit 测试中,我在 Junit 测试中执行以下操作:
@Before
public void setUp() throws Exception {
reportQueryParams = ReportQueryParams.builder()
.id("07")
.build();
}
@Test
public void tabSerializerTest() {
MetricsSerializer mockMonth = mock(MetricsSerializer.class);
when(mockMonth.getCurrentMonth()).thenReturn("July");
String tabSeparated = mockMonth.serializeMetrics(reportQueryParams);
String expected = new StringBuilder().append("074")
.append("\t")
.append("July")
.toString();
assertEquals(expected, tabSeparated);
}
我正在测试的功能:
public String serializeMetrics(final ReportQueryParams reportQueryParams) {
stringJoiner = new StringJoiner("\t");
addValueFromString(reportQueryParams.getId());
addValueFromString(getCurrentMonth());
return stringJoiner.toString();
}
public String getCurrentMonth() {
DateFormat monthFormat = new SimpleDateFormat("MMMMM");
return monthFormat.format(new Date());
}
private void addValueFromString(final String value) {
stringJoiner.add(value);
}
我的 ReportQueryParams 类:
public class ReportQueryParams {
private String id;
}
我在返回的实际数据中得到“null”,因此测试失败。我怎样才能解决这个问题?
解决方案
不要模拟您测试的对象。您所写的是“创建一个返回当月的七月的模拟对象”。但是这个模拟对象没有真正的行为,其他方法返回 null。
当你测试一个类时,你模拟了类所需的对象(为了隔离行为)而不是实际的类。在这里,您可以创建一个新的 MetricsSerializer(通过使用 new :) 并调用它的方法 serializeMethod 并与当前日期(而不是 7 月)进行比较。
不过,您编写课程的方式可能不是最好的可测试方式;)
推荐阅读
- jquery - TypeError:$ 不是函数 - toastr.js- AMD 和 SystemJS
- apache - AWS EC2 Apache 负载均衡器问题
- arrays - 如何使用数组 vb.net 将图片框图像的值传递给另一个图片框
- python - 如何将 2 个列表配对为 1 个列表
- angular - 选项卡路由更改
- javascript - 使用 Javascript 将带有 mySql 数据库的 php 文件转换为 html
- android - cmd文件中的adb命令(Windows)
- php - 如何将父节点复制到 SimpleXml 的当前节点
- java - java:同步块可以交错吗?
- angularjs - 更新范围属性不会更新视图