使用TJWSEmbeddedJaxrsServer + Mocktio测试简单的REST:测试结果不可重现

时间:2018-12-15 10:28:25

标签: rest testing mockito embedded-server

我正在尝试使用包含模拟服务的简单REST API进行测试。

编辑:我试图将本教程复制到这里:https://dzone.com/articles/how-test-rest-api-junit

如果我连续运行几次测试,可能会有两种结果:

  1. 测试运行正常,一切正常。
  2. 测试失败,因为响应为204-无内容。看起来,模拟的GWYServiceBean没有返回预期的Object。这导致错误和空洞的响应。我不知道问题出在哪里。也许你们其中一个可以在这里帮助我。

REST服务

@Inject
GWYServiceBean gwyServiceBean; // Should be mocked during the test

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public GWYDevice addDevice(GWYDevice gwyDevice) {
    return gwyServiceBean.add(gwyDevice);
}

使用Mockito / TJWSEmbeddedJaxrsServer进行单元测试

@RunWith(MockitoJUnitRunner.class)
public class GWYResourceTest {

@InjectMocks
private GWYResource sut = new GWYResource();
@Mock
private GWYServiceBean gwyServiceBeanMock;

private TJWSEmbeddedJaxrsServer server;
private ResteasyClient client;

@Before
public void setUp() {
    server = new TJWSEmbeddedJaxrsServer();
    server.getDeployment().getResources().add(sut);
    server.setPort(12345);
    server.start();
    client = new ResteasyClientBuilder().build();
}

@After
public void cleanUp() {
    client.close();
}

@Test
public void post() throws InterruptedException, ExecutionException {
    // Given
    String systemCode = "11111";
    String unitCode = "10000";
    long id = 1l;

    GWYDevice gwyDevice = new GWYDevice();
    gwyDevice.setSystemCode(systemCode);
    gwyDevice.setUnitCode(unitCode);

    GWYDevice persistedGwyDevice = new GWYDevice();
    persistedGwyDevice.setSystemCode(systemCode);
    persistedGwyDevice.setUnitCode(unitCode);
    persistedGwyDevice.setId(id);

    when(gwyServiceBeanMock.add(Mockito.any(GWYDevice.class))).thenReturn(persistedGwyDevice);

    // When
    Entity<GWYDevice> entity = Entity.json(gwyDevice);
    Response response = client.target("http://localhost:12345/gwy").request().post(entity);

    // Then
    assertTrue(response.getStatus() == OK.getStatusCode());
    GWYDevice returnedGwyDevice = response.readEntity(GWYDevice.class);
    assertNotNull(returnedGwyDevice.getId());
    assertEquals(gwyDevice.getSystemCode(), returnedGwyDevice.getSystemCode());
    assertEquals(gwyDevice.getUnitCode(), returnedGwyDevice.getUnitCode());
}

0 个答案:

没有答案