我有以下我要测试的Java代码。我遇到的困难是弄清楚如何验证对handleAppVersionRequest
的调用,实际上构建了AppVersionResponse
对象。有什么方法可以使用Mockito?
这里的代码是方法:
class MyClass {
public void handleAppVersionRequest(String dataStr,
final int dataChannelId) {
String ver = "1.0";
final AppVersionResponse resp = new AppVersionResponse(ver);
Timber.d("Sending data %s", resp.toString());
sendResponse(dataChannelId, getGson().toJson(resp));
}
}
这是测试的方法:
@Test
public void testHandleAppVersionRequest() throws Exception {
MyClass presenter = Mockito.spy(new MyClass());
String versionRequestJson = "{"command":1}";
when(presenter.getGson()).thenReturn(gSon);
presenter.handleAppVersionRequest(versionRequestJson,0);
// How do I verify that AppResponse object was constructed?
verify(presenter,times(1)).sendResponse(anyInt(),anyString());
}
如果您必须在单元测试期间测试对象的创建,则可以提取工厂,对其进行模拟测试,然后验证create
方法是在其中调用的。
同时,考虑花一些时间来查看一些嘲讽和单位测试的教程,例如这样。您应该选择一个将是"正在测试的系统"的类。不要间谍或嘲笑这堂课!相反,将模拟作为依赖项,您将用来测试类的行为。
这是从您的MyClass
提取的工厂:
class AppVersionResponseFactory {
AppVersionResponse create(String version) {
return new AppVersionResponse(version);
}
}
然后 class MyClass {
//dependencies that can now be mocked!
private final AppVersionResponseFactory appVersionResponseFactory;
private final Gson gson;
//pass the mockable dependencies in the constructor of the system under test!
public MyClass(AppVersionResponseFactory appVersionResponseFactory, Gson gson) {
this.appVersionResposeFactory = factory;
this.gson = gson;
}
public void handleAppVersionRequest(String dataStr, final int dataChannelId) {
String ver = "1.0";
AppVersionResponse resp = AppVersionResponseFactory.create(ver);
Timber.d("Sending data %s", resp.toString());
sendResponse(dataChannelId, gson.toJson(resp));
}
}
现在您的测试看起来像这样:
//mocks
AppVersionResponseFactory mockAppVersionResposeFactory;
Gson mockGson;
//system under test
MyClass myClass;
@Before
public void setUp() {
mockAppVersionResposeFactory = Mockito.mock(AppVersionResponseFactory.class);
mockGson = Mockito.mock(Gson.class);
myClass = new MyClass(mockGson, mockAppVersionResposeFactory);
}
@Test
public void testHandleAppVersionRequest() throws Exception {
String versionRequestJson = "{"command":1}";
myClass.handleAppVersionRequest(versionRequestJson, 0);
verify(appVersionResposeFactory).create("1.0");
}
请注意,尽管您的问题要求一种验证对象构造的方法,但更好的测试可能会测试该方法的最终结果,即使用正确的Datachannelid和正确的JSON调用了SendResponse。您可以在此答案中使用相同的技术来完成,即提取依赖项(也许是ResponseSender
?),将其传递到MyClass
的构造函数中,在测试中对其进行模拟,然后在其上调用验证。