我正在尝试使用包含模拟服务的简单REST API进行测试。
编辑:我试图将本教程复制到这里:https://dzone.com/articles/how-test-rest-api-junit
如果我连续运行几次测试,可能会有两种结果:
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());
}