26

我是 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);

    }

这是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();
    }

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

有人可以帮帮我吗?

4

5 回答 5

24

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

并且您需要验证该合同是否由该方法履行。

Mockito 在这里有什么帮助?好吧,如果您在没有 Mockito 的情况下测试此方法,则需要一个 real DataStoreService,并且您需要验证该实体已在此 real 中正确创建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
    }
}

现在在您的测试方法中,您可以执行以下操作:

@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
}
于 2012-05-27T16:50:01.230 回答
3

您所说的听起来更像是集成测试和 Mockito(或任何其他模拟框架)对您没有多大用处。

如果您想对您编写的代码进行单元测试,Mockito 无疑是一个有用的工具。

我建议您阅读更多关于模拟/单元测试以及应该在哪些情况下使用它的信息。

于 2012-05-27T15:58:08.293 回答
2

Mockito(通常)用于测试部分代码;例如,如果您正在使用 REST 服务,但不想进行全栈测试,您可以模拟连接到 REST 服务的服务,从而允许您准确、一致地测试特定行为。

要在不访问数据库的情况下测试 REST 服务的内部部分(例如,特定的服务方法),您可以模拟 DB 子系统,只允许测试服务内部,而不涉及数据库。此测试属于 REST 服务模块,而不是客户端。

要测试 REST 服务本身,您将使用一个实际的客户端库,创建一个全栈集成测试。Mockito 可以在这里用来模拟与 REST 服务消费无关的客户端部分。

于 2012-05-27T16:03:44.930 回答
2

最好的方法是使用wiremock 添加以下依赖项 com.github.tomakehurst wiremock 2.4.1 org.igniterealtime.smack smack-core 4.0.6

如下图定义和使用wiremock

@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);

String response ="Hello world";
StubMapping responseValid = stubFor(get(urlEqualTo(url)).withHeader("Content-Type", equalTo("application/json"))
        .willReturn(aResponse().withStatus(200)
                .withHeader("Content-Type", "application/json").withBody(response)));
于 2016-12-01T10:45:55.007 回答
0

我同意这不是单元测试而是集成测试,无论如何你宁愿看看球衣和嵌入式灰熊服务器测试。总结一下,这段代码在 localhost:8888 启动了 grizzly 服务器(也可以启动数据库),然后设置客户端的 jersey 客户端并发送一个 POST 请求,该请求应该被测试。这是一个集成,因为您正在测试服务器和数据库,但是您可以使用 mockito 来模拟数据库,但这取决于您的服务器和数据库的绑定程度。

(使用 jersey 1.11 和 grizzly 2.2 进行测试)

    @BeforeClass
    public static void setUpClass() throws Exception {
        // starts grizzly
        Starter.start_grizzly(true);
        Thread.sleep(4000);
    }

    @Before
    public void setUp() throws Exception {
        client = new Client();
        webResource = client.resource("http://localhost:8888");
    }   

    @Test
    public void testPostSchemaDatabase() throws Exception {
        {
            String DatabaseSchema = "{ database_schema : {...}}";
            logger.info("REST client configured to send: "  + DatabaseSchema);
            ClientResponse response =  
                    webResource
                             .path("/initialize")
                             .type("application/json")
                             .post(ClientResponse.class, DatabaseSchema);
            //wait for the server to process
            Thread.sleep(2000);
            assertEquals(response.getStatus(), 204);    
            //test the response
        }       
    }

    @After
    public void after() throws JSONException
    {
            //probably you want to delete the schema at database and stop the server

}
于 2012-05-28T06:42:07.247 回答