I am a beginner in JUnit.
I want to create a test to get all the product
s and to get the product
s by id
.
This is my Java code:
@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);
}
}
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 Produit
s 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 the actual tests for RESTful resources, rest-assured being a good one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With