Introduction
An open-source Java framework called Dropwizard is used to quickly create high-performance RESTful web services. It puts a few well-known libraries together to create a little package. It primarily uses the Jetty, Jersey, Jackson, JUnit, and Guava libraries. It also uses a library of metrics that it has created.
We'll learn about Dropwizard's testing implementation in this article.
Dropwizard-Testing
Instead of deploying your apps to an application server or web server, Dropwizard specifies a primary method that starts the Jetty server as an independent process. To run the application, Dropwizard only advises using Jetty; Tomcat and other web services are not supported.
With the aid of Dropwizard, developers can quickly bootstrap their projects and package their software as standalone services that are simple to set up and deploy. It is also relatively easy to utilize and put into practice.
Testing Resources
Some resources are better suited to a more comprehensive strategy. However, many resource classes can be tested simply by calling the methods on the class in a test. Use ResourceExtension to load a specified resource instance into an in-memory Jersey server for these:
//must to import
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import io.dropwizard.testing.junit5.ResourceExtension;
import java.util.Optional;
import org.junit.jupiter.api.*;
import javax.ws.rs.core.Response;
@ExtendWith(DropwizardExtensionsSupport.class)
class PersonResourceTest {
private static final ResourceExtension Extens = ResourceExtension.builder()
.addResource(new PersonResource(DAO))
.build();
private static final PersonDAO D_A_O= mock(PersonDAO.class);
private Person find_person;
@BeforeEach
void setup() {
find_person = new Person();
find_person.setId(1L);
//pre-requisite
}
@AfterEach
void tearDown() {
reset(D_A_O);
//post-requisite
}
@Testing
void getPersonSuccess() {
when(D_A_O.findById(1L)).thenReturn(Optional.of(person));
Person find = EXT.target("/people/1").request().get(Person.class);
assertThat(found.getId()).isEqualTo(find_person.getId());
verify(D_A_O).findById(1L);
}
@Testing
void getPersonNotFound() {
when(D_A_O.findById(2L)).thenReturn(Optional.empty());
final Response finalres = EXT.target("/people/2").request().get();
assertThat(finalres.getStatusInfo().getStatusCode()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode());
verify(D_A_O).findById(2L);
}
}
Create a ResourceExtension using its Builder, then populate it with the various resource instances you want to test. Builder#addResource(Object). To instruct Dropwizard to look for any fields of ResourceExtension, annotate the class with the @ExtendWith(DropwizardExtensionsSupport.class) annotation.
Use #target(String path) in your tests to initialize a request to communicate with and test your instances.
ResourceExtension testing will handle all serialization, deserialization, and validation within the HTTP process, so opening a port is unnecessary.
Testing Client Implementations
You may test your HTTP client code by creating a JAX-RS resource as a test double and using the DropwizardClientExtension to start and stop a straightforward Dropwizard application containing your test doubles. This can help you eliminate circular dependencies in your projects or speed up test runs.
@ExtendWith(DropwizardExtensionsSupport.class)
class Client_Test {
@Path("/ping")
public static class Ping_Resource {
@GET
public String ping() {
return "ppong";
}
}
private static final DropwizardClientExtension Extern = new DropwizardClientExtension(new PingResource());
@Test
void shouldPing() throws IOException {
final URL URL = new URL(Extern.baseUri() + "/ping");
//take input for the response
final String finalres = new BufferedReader(new InputStreamReader(URL.openStream())).readLine();
assertEquals("ppong", finalres);
}
}
Specifically, the DropwizardClientExtension handles:
- Making a straightforward default configuration.
- Creating a specific application.
- Modifying the application removes a fake health check to disable the startup warning.
- Your test duplicates for JAX-RS resources should be added to the Dropwizard application.
- Picking a random free port number (necessary for running tests in parallel).
- Launching the Dropwizard program that contains the test duplicates.
- Putting an end to the Dropwizard program that contains the test doubles.
Testing Database Interactions
In Dropwizard, the @UnitOfWork annotation used on resource methods is used to control database access. A DAOTestExtension is offered that creates a Hibernate SessionFactory in case you want to test database-layer code independently.
@ExtendWith(DropwizardExtensionsSupport.class)
public class Testing_DataBase{
public DAOTestExtension DB= DAOTestExtension.newBuilder().addEntityClass(FooEntity.class).build();
private FooDAO foo_DAO;
@Pre-requisite
public void setUp() {
foo_DAO = new FooDAO(DB.getSessionFactory());
}
@Test
public void createsFunc() {
FooEntity foo_Entity = new FooEntity("bar");
long id_new = database.inTransaction(() -> {
return fooDAO.save(foo_Entity);
});
assertThat(foo_Entity.getId_new, notNullValue());
}
@Test
public void roundtripsFoo() {
long id_new = database.inTransaction(() -> {
return fooDAO.save(new FooEntity("baz"));
});
FooEntity foo_Entity = fooDAO.get(id);
assertThat(foo_Entity.getFoo(), equalTo("baz"));
}
}
DAO Test Extension
- Use an H2 in-memory database to create a straightforward default Hibernate configuration.
- Provides a function for carrying out database operations during a transaction and a SessionFactory instance that may be provided to, for example, a subclass of AbstractDAO