如何使用mockito测试REST服务?

Ion*_*zan 25 java rest unit-testing mockito

我是Java单元测试的新手,我听说Mockito框架非常适合测试目的.

我开发了一个REST服务器(CRUD方法),现在我想测试它,但我不知道怎么做?

更多我不知道这个测试程序应该如何开始.我的服务器应该在localhost上工作,然后在该url上调用(例如localhost:8888)?

这是我到目前为止所尝试的,但我很确定这不是正确的方法.

    @Test
    public void testInitialize() {
        RESTfulGeneric rest = mock(RESTfulGeneric.class);

        ResponseBuilder builder = Response.status(Response.Status.OK);

        builder = Response.status(Response.Status.OK).entity(
                "Your schema was succesfully created!");

        when(rest.initialize(DatabaseSchema)).thenReturn(builder.build());

        String result = rest.initialize(DatabaseSchema).getEntity().toString();

        System.out.println("Here: " + result);

        assertEquals("Your schema was succesfully created!", result);

    }
Run Code Online (Sandbox Code Playgroud)

这是initialize方法的代码.

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/initialize")
    public Response initialize(String DatabaseSchema) {

        /** Set the LogLevel to Info, severe, warning and info will be written */
        LOGGER.setLevel(Level.INFO);

        ResponseBuilder builder = Response.status(Response.Status.OK);

        LOGGER.info("POST/initialize - Initialize the " + user.getUserEmail()
                + " namespace with a database schema.");

        /** Get a handle on the datastore itself */
        DatastoreService datastore = DatastoreServiceFactory
                .getDatastoreService();


        datastore.put(dbSchema);

        builder = Response.status(Response.Status.OK).entity(
                "Your schema was succesfully created!");
        /** Send response */
        return builder.build();
    }
Run Code Online (Sandbox Code Playgroud)

在这个测试用例中,我想将一个Json字符串发送到服务器(POST).如果一切顺利,那么服务器应回复"您的架构已成功创建!".

有人可以帮帮我吗?

JB *_*zet 23

好.因此,该方法的合同如下:将输入字符串解析为JSON,BAD_REQUEST如果它无效则返回.如果它有效,请在datastore具有各种属性(您知道它们)的实体中创建一个实体,然后发回OK.

您需要验证该方法是否满足此合同.

Mockito在哪里帮忙?好吧,如果你在没有Mockito的情况下测试这个方法,你需要一个真实的DataStoreService,你需要验证实体是否已经在这个真实中正确创建DataStoreService.这是您的测试不再是单元测试的地方,这也是测试太复杂,太长,太难以运行的地方,因为它需要复杂的环境.

Mockito可以通过DataStoreService模拟对以下内容的依赖来提供帮助:您可以创建模拟DataStoreService,并initialize()在测试中调用方法时验证是否使用适当的实体参数调用了此模型.

要做到这一点,您需要能够将其注入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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在您的测试方法中,您可以:

@Test
public 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
}
Run Code Online (Sandbox Code Playgroud)