<commit_before>.. _manual-testing:

##################
Testing Dropwizard
##################

.. highlight:: text

.. rubric:: The ``dropwizard-testing`` module provides you with some handy classes for testing
            your :ref:`representation classes <man-core-representations>`
            and :ref:`resource classes <man-core-resources>`. It also provides a JUnit rule
            for full-stack testing of your entire app.

.. _man-testing-representations:

Testing Representations
=======================

While Jackson's JSON support is powerful and fairly easy-to-use, you shouldn't just rely on
eyeballing your representation classes to ensure you're actually producing the API you think you
are. By using the helper methods in `FixtureHelpers` you can add unit tests for serializing and
deserializing your representation classes to and from JSON.

Let's assume we have a ``Person`` class which your API uses as both a request entity (e.g., when
writing via a ``PUT`` request) and a response entity (e.g., when reading via a ``GET`` request):

.. code-block:: java

    public class Person {
        private String name;
        private String email;

        private Person() {
            // Jackson deserialization
        }

        public Person(String name, String email) {
            this.name = name;
            this.email = email;
        }

        @JsonProperty
        public String getName() {
            return name;
        }

        @JsonProperty
        public void setName(String name) {
            this.name = name;
        }

        @JsonProperty
        public String getEmail() {
            return email;
        }

        @JsonProperty
        public void setEmail(String email) {
            this.email = email;
        }

        // hashCode
        // equals
        // toString etc.
    }

.. _man-testing-representations-fixtures:

Fixtures
--------

First, write out the exact JSON representation of a ``Person`` in the
``src/test/resources/fixtures`` directory of your Dropwizard project as ``person.json``:

.. code-block:: javascript

    {
        "name": "<NAME>",
        "email": "<EMAIL>"
    }

.. _man-testing-representations-serialization:

Testing Serialization
---------------------

Next, write a test for serializing a ``Person`` instance to JSON:

.. code-block:: java

    import static io.dropwizard.testing.FixtureHelpers.*;
    import static org.assertj.core.api.Assertions.assertThat;
    import io.dropwizard.jackson.Jackson;
    import org.junit.Test;
    import com.fasterxml.jackson.databind.ObjectMapper;

    public class PersonTest {

        private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

        @Test
        public void serializesToJSON() throws Exception {
            final Person person = new Person("<NAME>", "<EMAIL>");

            final String expected = MAPPER.writeValueAsString(
                    MAPPER.readValue(fixture("fixtures/person.json"), Person.class));

            assertThat(MAPPER.writeValueAsString(person)).isEqualTo(expected);
        }
    }

This test uses `AssertJ assertions`_ and JUnit_ to test that when a ``Person`` instance is serialized
via Jackson it matches the JSON in the fixture file. (The comparison is done on a normalized JSON
string representation, so formatting doesn't affect the results.)

.. _AssertJ assertions: http://assertj.org/assertj-core-conditions.html
.. _JUnit: http://www.junit.org/

.. _man-testing-representations-deserialization:

Testing Deserialization
-----------------------

Next, write a test for deserializing a ``Person`` instance from JSON:

.. code-block:: java

    import static io.dropwizard.testing.FixtureHelpers.*;
    import static org.assertj.core.api.Assertions.assertThat;
    import io.dropwizard.jackson.Jackson;
    import org.junit.Test;
    import com.fasterxml.jackson.databind.ObjectMapper;

    public class PersonTest {

        private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

        @Test
        public void deserializesFromJSON() throws Exception {
            final Person person = new Person("<NAME>", "<EMAIL>");
            assertThat(MAPPER.readValue(fixture("fixtures/person.json"), Person.class))
                    .isEqualTo(person);
        }
    }


This test uses `AssertJ assertions`_ and JUnit_ to test that when a ``Person`` instance is
deserialized via Jackson from the specified JSON fixture it matches the given object.

.. _man-testing-resources:

Testing Resources
=================

While many resource classes can be tested just by calling the methods on the class in a test, some
resources lend themselves to a more full-stack approach. For these, use ``ResourceTestRule``, which
loads a given resource instance in an in-memory Jersey server:

.. _man-testing-resources-example:

.. code-block:: java

    import static org.assertj.core.api.Assertions.assertThat;
    import static org.mockito.Mockito.*;

    public class PersonResourceTest {

        private static final PeopleStore dao = mock(PeopleStore.class);

        @ClassRule
        public static final ResourceTestRule resources = ResourceTestRule.builder()
                .addResource(new PersonResource(dao))
                .build();

        private final Person person = new Person("blah", "<EMAIL>");

        @Before
        public void setup() {
            when(dao.fetchPerson(eq("blah"))).thenReturn(person);
            // we have to reset the mock after each test because of the
            // @ClassRule, or use a @Rule as mentioned below.
            reset(dao);
        }

        @Test
        public void testGetPerson() {
            assertThat(resources.client().target("/person/blah").request().get(Person.class))
                    .isEqualTo(person);<commit_msg>Should reset mock DAO in tear down<commit_after>.. _manual-testing:

##################
Testing Dropwizard
##################

.. highlight:: text

.. rubric:: The ``dropwizard-testing`` module provides you with some handy classes for testing
            your :ref:`representation classes <man-core-representations>`
            and :ref:`resource classes <man-core-resources>`. It also provides a JUnit rule
            for full-stack testing of your entire app.

.. _man-testing-representations:

Testing Representations
=======================

While Jackson's JSON support is powerful and fairly easy-to-use, you shouldn't just rely on
eyeballing your representation classes to ensure you're actually producing the API you think you
are. By using the helper methods in `FixtureHelpers` you can add unit tests for serializing and
deserializing your representation classes to and from JSON.

Let's assume we have a ``Person`` class which your API uses as both a request entity (e.g., when
writing via a ``PUT`` request) and a response entity (e.g., when reading via a ``GET`` request):

.. code-block:: java

    public class Person {
        private String name;
        private String email;

        private Person() {
            // Jackson deserialization
        }

        public Person(String name, String email) {
            this.name = name;
            this.email = email;
        }

        @JsonProperty
        public String getName() {
            return name;
        }

        @JsonProperty
        public void setName(String name) {
            this.name = name;
        }

        @JsonProperty
        public String getEmail() {
            return email;
        }

        @JsonProperty
        public void setEmail(String email) {
            this.email = email;
        }

        // hashCode
        // equals
        // toString etc.
    }

.. _man-testing-representations-fixtures:

Fixtures
--------

First, write out the exact JSON representation of a ``Person`` in the
``src/test/resources/fixtures`` directory of your Dropwizard project as ``person.json``:

.. code-block:: javascript

    {
        "name": "<NAME>",
        "email": "<EMAIL>"
    }

.. _man-testing-representations-serialization:

Testing Serialization
---------------------

Next, write a test for serializing a ``Person`` instance to JSON:

.. code-block:: java

    import static io.dropwizard.testing.FixtureHelpers.*;
    import static org.assertj.core.api.Assertions.assertThat;
    import io.dropwizard.jackson.Jackson;
    import org.junit.Test;
    import com.fasterxml.jackson.databind.ObjectMapper;

    public class PersonTest {

        private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

        @Test
        public void serializesToJSON() throws Exception {
            final Person person = new Person("<NAME>", "<EMAIL>");

            final String expected = MAPPER.writeValueAsString(
                    MAPPER.readValue(fixture("fixtures/person.json"), Person.class));

            assertThat(MAPPER.writeValueAsString(person)).isEqualTo(expected);
        }
    }

This test uses `AssertJ assertions`_ and JUnit_ to test that when a ``Person`` instance is serialized
via Jackson it matches the JSON in the fixture file. (The comparison is done on a normalized JSON
string representation, so formatting doesn't affect the results.)

.. _AssertJ assertions: http://assertj.org/assertj-core-conditions.html
.. _JUnit: http://www.junit.org/

.. _man-testing-representations-deserialization:

Testing Deserialization
-----------------------

Next, write a test for deserializing a ``Person`` instance from JSON:

.. code-block:: java

    import static io.dropwizard.testing.FixtureHelpers.*;
    import static org.assertj.core.api.Assertions.assertThat;
    import io.dropwizard.jackson.Jackson;
    import org.junit.Test;
    import com.fasterxml.jackson.databind.ObjectMapper;

    public class PersonTest {

        private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

        @Test
        public void deserializesFromJSON() throws Exception {
            final Person person = new Person("<NAME>", "<EMAIL>");
            assertThat(MAPPER.readValue(fixture("fixtures/person.json"), Person.class))
                    .isEqualTo(person);
        }
    }


This test uses `AssertJ assertions`_ and JUnit_ to test that when a ``Person`` instance is
deserialized via Jackson from the specified JSON fixture it matches the given object.

.. _man-testing-resources:

Testing Resources
=================

While many resource classes can be tested just by calling the methods on the class in a test, some
resources lend themselves to a more full-stack approach. For these, use ``ResourceTestRule``, which
loads a given resource instance in an in-memory Jersey server:

.. _man-testing-resources-example:

.. code-block:: java

    import static org.assertj.core.api.Assertions.assertThat;
    import static org.mockito.Mockito.*;

    public class PersonResourceTest {

        private static final PeopleStore dao = mock(PeopleStore.class);

        @ClassRule
        public static final ResourceTestRule resources = ResourceTestRule.builder()
                .addResource(new PersonResource(dao))
                .build();

        private final Person person = new Person("blah", "<EMAIL>");

        @Before
        public void setup() {
            when(dao.fetchPerson(eq("blah"))).thenReturn(person);
        }

        @After
        public void tearDown(){
            // we have to reset the mock after each test because of the
            // @ClassRule, or use a @Rule as mentioned below.
            reset(dao);
        }

        @Test
        public void testGetPerson() {
            assertThat(resources.client().target("/person/blah").request().get(Person.class))
                    .isEqualTo(person);
{'fraction_non_alphanumeric': 0.11192943392994777, 'fraction_numerical': 0.0, 'mean_word_length': 2.6143608789848343, 'pattern_counts': {'":': 4, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4415259', 'n_tokens_mistral': 3055, 'n_tokens_neox': 2939, 'n_words': 1019}