java.lang.AssertionError: Status Expected :200 Actual :500

Viewed 369

I wrote a small code to test my Controller and used mockito in this regard. The code is shown below with correct syntaxes

public class ApiTest {

    private MockMvc mockMvc;

    @InjectMocks
    private PersonController personController;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
    }

    @Test
    public void testPersonController() throws Exception{

        //String jsonResult = "{\"name\": \"Müller\", \"lastName\": \"Hans\", \"zipCode\": \"67742\", \"city\": \"Lauterecken\", \"color\": \"blau\", \"id\": 1}";

        mockMvc.perform(MockMvcRequestBuilders.
                get("/api/v1/person/persons/1").
                accept(MediaType.APPLICATION_JSON)).
                andDo(print()).
                andExpect(status().isOk()).
                andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")).
                andExpect(MockMvcResultMatchers.jsonPath("$name").value("Müller"))
                .andExpect(MockMvcResultMatchers.jsonPath("$lastName").value("Hans")).
                 andExpect(MockMvcResultMatchers.jsonPath("$zipCode").value("67742"))
                .andExpect(MockMvcResultMatchers.jsonPath("$city").value("Lauterecken"))
                .andExpect(MockMvcResultMatchers.jsonPath("$color").value("blau"));

    }

}

I am receiving an assertion error as shown below

java.lang.AssertionError: Status 
Expected :200
Actual   :500

Can anyone help me where I am going wrong?

1 Answers

Looks like you're not fully utilizing what Spring Boot offers to test controllers.

When you're testing with MockMvc:

  • annotate your class with @WebMvcTest
  • use @MockBean to mock any collaborators this controller depends on
  • autowire MockMvc instead of creating it
@WebMvcTest(PersonController.class)
public class ApiTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    SomeService someService; // only if controller has dependencies on any components

    @Test
    void aTest() {
        mockMvc.perform(...)
        // ...
    }

Related