I'm trying to test a simple rest API with a mocked service included. If I run the test several times in a row, there are two possible outcomes:
- The test runs fine and everything is OK.
- The test fails because the response is 204 - No Content. It looks like the mocked GWYServiceBean does not return an Object as intended. This leads to a wrong and emptpy response. I can't figure out where the problem is. Maybe one of you can help me out here.
The REST Service
@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);
}
** Unit Test with 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());
}
Aucun commentaire:
Enregistrer un commentaire