我正在学习单元测试,我遇到了创建最终检查测试用例是否正确的问题。通常我会尝试创建验证,例如通过 assertEquals()
。但是,当无法像这样进行测试时,建议做什么?
我有这样一个类:
public class Landlord {
private Map<String, ChannelHandlerContext> currentOccupier;
private static Landlord instance;
public Landlord() {
currentOccupier = new HashMap<>();
}
public static Landlord getInstance {
//return instance
}
public void add(Occupier occupier){
currentOccupier.put("test", occupier.getChannelHandlerContext());
}
}
现在我尝试像这样测试这个方法:
public class LandlordTest {
private Landlord landlord;
@Mock
private Occupier occupier;
@Mock
private ChannelHandlerContext channelHandlerContext;
@BeforeEach
void setUp() {
occupier = mock(Occupier.class);
channelHandlerContext = mock(ChannelHandlerContext.class);
landlord = Landlord.getInstance();
when(occupier.getChannelHandlerContext()).thenReturn(channelHandlerContext);
}
public void add(Occupier occupier){
addedOccupier.put(occupier.getChannelHandlerContext());
//adding succeded
}
}
也许在这个简短的示例中不需要对其进行测试,但是有没有办法验证添加方法是否成功?通常在这种情况下,我会尝试类似的方法:assertEquals(currentOccupier.size(), 1)
,但在这里我无法访问实例的 hashMap 来执行此操作。还有另一种方法来验证添加它的正确行为吗?
最佳答案
这个assertEquals(currentOccupier.size(), 1)
确实不够用。
您想要断言 map 包含您在 map 中添加的条目。
该断言太肤浅了:它既不检查键的值也不检查值的值。
你应该做类似的事情:
ChannelHandlerContext actualContext = landLord.get("test");
assertSame(addedContext, actualContext);
// or assertEquals if the instances may differ because you do some defensive copy in add()
另请注意,您在这里模拟了一些不需要模拟的东西:occupier
和 channelHandlerContext
构成了模型的一部分。您应该能够在测试框架中提供它们的“正常”实例。
在这里,您有两种大致的方法来执行此操作:
1) 在要测试的类中添加一个公共(public)方法以找到一个 ChannelHandlerContext
:
public ChannelHandlerContext get(String name){
currentOccupier.get(name);
}
仅在提供此访问权限可接受的情况下执行此操作。
如果您无法添加公共(public)方法,请添加包级方法,因为这不构成公开 API 的一部分。
2) 使用反射 api(本质上是 Class.getDeclaredField(String)
和 Field.get()
)从被测实例中检索 map 实例,然后断言它包含“测试”键的预期 ChannelHandlerContext
实例。
关于java - 如果无法验证,如何检查测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56153735/