CooperShelly CooperShelly - 2 months ago 20
Java Question

How to create a JUNIT Test for REST Web Service?

I am a beginner in

JUNIT
.
I want to create
test
to get all the
product
and to get the
products
by
id
.
This is my following
class
:

@Path("/produits")
@Produces("application/json")
public class ProduitResource {

public ProduitResource() {
}

@GET
public List<Produit> getProduits() {
System.out.println("getProduits");

return ReadXMLFile.getProduits();
}

@GET
@Path("numProduit-{id}")
public Produit getProduit(@PathParam("id") String numProduit) {
System.out.println("getProduit");

for (Produit current : ReadXMLFile.getProduits()) {
if (numProduit.equals(current.getNumProduit())) {
return current;
}
}
return null;
}

@GET
@Path("/search")
public List<Produit> searchProduitsByCriteria(@QueryParam("departure") String departure, @QueryParam("arrival") String arrival, @QueryParam("arrivalhour") String arrivalHour) {
System.out.println("searchProduitsByCriteria");

return ReadXMLFile.getProduits().subList(0, 2);
}
}

Answer

Presuming that what you want is to make a unit test, as opposed to an integration, functional or another type of test, you should simply instantiate ProduitResource and run tests on it:

@Test
public void testFetchingById() {
   ProduitResource repo = new ProduitResource();
   Produit prod = repo.getProduit("prod123");
   assertNotNull(prod);
   assertEquals(prod.getId(), "prod123");
}

Doing this might require mocking the environment, in your case you might need to mock whatever the Produits are being fetched from.

If you were to actually fire HTTP requests at it, this would require a server running and would no longer constitute a unit test (as you'd be testing more than just this unit's own functionality). To do this, you could make your build tool start up the server before running tests (Jetty Maven plugin for example can be used here to start Jetty in pre-integration-test phase), or you could make JUnit do it in a preparation step (@BeforeClass) as described here. Similar logic for shutting the server down (use post-integration-test phase in Maven or @AfterClass in JUnit).

There's many libraries that help you write actual tests for RESTful resources, rest-assured being a good one.

Comments