好。因此,该方法的约定如下:将输入字符串解析为JSON,
BAD_REQUEST如果无效,则将其发送回。如果有效,请在中创建
datastore具有各种属性的实体(您知道它们),然后将其发送回去
OK。
并且您需要验证该方法是否满足了该合同。
Mockito在这里有什么帮助?好吧,如果您在没有Mockito的情况下测试此方法,则需要一个real
DataStoreService,并且需要验证已在此real中正确创建了实体
DataStoreService。这是您的测试不再是单元测试的地方,这也是测试太复杂,太长且难以运行的原因,因为它需要一个复杂的环境。
Mockito可以通过
DataStoreService模拟对的依赖来提供帮助:您可以创建的模拟
DataStoreService,并
initialize()在测试中调用方法时验证是否确实使用适当的entity参数调用了该模拟。
为此,您需要能够将注入
DataStoreService到被测对象中。可以通过以下方式重构对象一样简单:
public class MyRestService { private DataStoreService dataStoreService; // constructor used on the server public MyRestService() { this.dataStoreService = DatastoreServiceFactory.getDatastoreService(); } // constructor used by the unit tests public MyRestService(DataStoreService dataStoreService) { this.dataStoreService = dataStoreService; } public Response initialize(String DatabaseSchema) { ... // use this.dataStoreService instead of datastore }}现在,在您的测试方法中,您可以执行以下操作:
@Testpublic void testInitializeWithGoodInput() { DataStoreService mockDataStoreService = mock(DataStoreService.class); MyRestService service = new MyRestService(mockDataStoreService); String goodInput = "..."; Response response = service.initialize(goodInput); assertEquals(Response.Status.OK, response.getStatus()); ArgumentCaptor<Entity> argument = ArgumentCaptor.forClass(Entity.class); verify(mock).put(argument.capture()); assertEquals("the correct kind", argument.getValue().getKind()); // ... other assertions}


