2
\$\begingroup\$

I'm beginner java programmer and would like to ask you to take a look at my code. I wrote small rest service among with tests. Now I have to questions to ask.

The test methods:

@Transactional
public class CustomerControllerTests extends RestApplicationTests{

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup(){
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();
    }

    @Test
    public void getRequestSent_then200IsRecived() throws Exception{
        mockMvc.perform(get("/customers"))
                .andExpect(status().isOk());
    }

    @Test
    public void getRequestSend_thenJSONisRecived() throws Exception{
        mockMvc.perform(get("/customers"))
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
    }

    @Test
    public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsRecived() throws Exception{
        final String id = "666634443255233321";
        mockMvc.perform(get("/customers/" + id))
                .andExpect(status().isNotFound());
    }

    @Test
    public void givenPutRequest_whenRequestBodyIsValid_then200IsRecived() throws Exception{

        Customer customerStub = new Customer.Builder()
                .firstName("Adam")
                .lastName("Nawalka")
                .town("Boston")
                .customerId(8888)
                .build();

        Gson gson = new Gson();
        String entityAsJson = gson.toJson(customerStub);

        mockMvc.perform(put("/customers").with(anonymous())
                .content(entityAsJson)
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());

    }

    @Test
    public void givenPutRequest_whenIdIsMissing_thenIllegalArgumentExceptionAsCause() throws Exception{

        Customer customerStub = new Customer.Builder()
                .firstName("Adam")
                .lastName("Nawalka")
                .town("Boston")
                .build();

        Gson gson = new Gson();
        String entityAsJson = gson.toJson(customerStub);

        try{
        mockMvc.perform(put("/customers")
                .content(entityAsJson)
                .contentType(MediaType.APPLICATION_JSON_UTF8));
        }
        catch(NestedServletException e){
            Assert.assertEquals(NestedServletException.class, e.getClass());
            Assert.assertEquals(IllegalArgumentException.class, e.getCause().getClass());
            Assert.assertEquals("Can not update with id equal to 0", e.getCause().getLocalizedMessage());
        }
    }

    @Test
    public void givenPutRequest_whenEntityIsNotCompatible_then400BadRequest() throws Exception{

        Customer customerStub = new Customer.Builder()
                .firstName("Adam")
                .town("Boston")
                .customerId(8888)
                .build();

        Gson gson = new Gson();
        String entityAsJson = gson.toJson(customerStub);

        mockMvc.perform(put("/customers")
                .content(entityAsJson)
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isBadRequest());

    }

    @Test
    public void givenPutRequest_whenEntityIsNotCompatible_thenExplanationInBody() throws Exception{

        Customer customerStub = new Customer.Builder()
                .firstName("Adam")
                .town("Boston")
                .customerId(8888)
                .build();

        Gson gson = new Gson();
        String entityAsJson = gson.toJson(customerStub);

        mockMvc.perform(put("/customers")
                .content(entityAsJson)
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(content()
                        .string("Entity contains forbidden values: "
                                + "Can not update entity with field \"lastName\" set to: null"));
    }

    @Test
    public void givenPutRequest_whenEntityIsNotCompatible_thenDataInputException() throws Exception{
        Customer customerStub = new Customer.Builder()
                .firstName("Adam")
                .town("Boston")
                .customerId(8888)
                .build();

        Gson gson = new Gson();
        String entityAsJson = gson.toJson(customerStub);

        try{
        mockMvc.perform(put("/customers")
                .content(entityAsJson)
                .contentType(MediaType.APPLICATION_JSON_UTF8));
        }
        catch(DataInputException e){
            Assert.assertEquals(DataInputException.class, e.getClass());
        }
    }

    @Test
    public void givenPostRequest_whenRequestBodyIsValid_then200IsRecived() throws Exception{

        Customer customerStub = new Customer.Builder()
                .firstName("Adam")
                .lastName("Nawalka")
                .town("Boston")
                .customerId(8888)
                .build();

        Gson gson = new Gson();
        String entityAsJson = gson.toJson(customerStub);

        mockMvc.perform(post("/customers")
                .content(entityAsJson)
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isCreated());

    }

    @Test
    public void givenDeleteRequest_whenUserExists_then204NoContent() throws Exception{
        mockMvc.perform(delete("/customers/1"))
                .andExpect(status().isNoContent());
    }


}
  1. Is my approach separating different results to different methods correct? I could do more compressed assertions checking for exceptions and result body and result status in one method. Isnt it better approach?

  2. To run the tests I'm using my "main" database, Is it possible to somehow mock my database so that I could have full controll during the test what's in the database and did not have to use the "main" db?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  1. You are absolutely right to have each test in a separate method. If a test should fail later on, this quickly gives you a clear idea on what tests fail and how bad the problem is.

  2. We use H2 for testing our database components. H2 is an in-memory database which only lives for as long as the JVM running the tests. More information on H2 here.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.