CooperShelly CooperShelly - 1 month ago 4x
Java Question

How to create a JUNIT Test for REST Web Service?

I am a beginner in

I want to create
to get all the
and to get the
This is my following

public class ProduitResource {

public ProduitResource() {

public List<Produit> getProduits() {

return ReadXMLFile.getProduits();

public Produit getProduit(@PathParam("id") String numProduit) {

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

public List<Produit> searchProduitsByCriteria(@QueryParam("departure") String departure, @QueryParam("arrival") String arrival, @QueryParam("arrivalhour") String arrivalHour) {

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


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:

public void testFetchingById() {
   ProduitResource repo = new ProduitResource();
   Produit prod = repo.getProduit("prod123");
   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.