有以下类(class):
class ToTest{
@Autowired
private Service service;
public String make(){
//do some calcs
obj.setParam(param);
String inverted = service.execute(obj);
return "<" + inverted.toString() + ">";
}
}
我想添加一个测试来断言 service.execute 是用一个带有参数 X 的对象调用的。
我会通过验证来做到这一点。我想模拟这个调用并让它返回可测试的东西。我带着期望这样做。
@Tested
ToTest toTest;
@Injected
Service service;
new NonStrictExpectations(){
{
service.exceute((CertainObject)any)
result = "b";
}
};
toTest.make();
new Verifications(){
{
CertainObject obj;
service.exceute(obj = withCapture())
assertEquals("a",obj.getParam());
}
};
我在 obj.getParam() 上得到一个空指针。显然验证不起作用。如果我删除期望它会起作用,但我会在 inverted.toString() 中得到一个空指针。
你们将如何完成这项工作?
最佳答案
以下测试类对我来说工作正常,使用 JMockit 1.4:
public class TempTest
{
static class CertainObject
{
private String param;
String getParam() { return param; }
void setParam(String p) { param = p; }
}
public interface Service { String execute(CertainObject o); }
public static class ToTest
{
private Service service;
public String make()
{
CertainObject obj = new CertainObject();
obj.setParam("a");
String inverted = service.execute(obj);
return "<" + inverted + ">";
}
}
@Tested ToTest toTest;
@Injectable Service service;
@Test
public void temp()
{
new NonStrictExpectations() {{
service.execute((CertainObject) any);
result = "b";
}};
toTest.make();
new Verifications() {{
CertainObject obj;
service.execute(obj = withCapture());
assertEquals("a", obj.getParam());
}};
}
}
你能展示一个失败的完整示例测试吗?
关于java - 我如何在 JMockit 中期望和验证相同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18868568/