'JUnit @Before method does not run

I'm writing tests for REST controller which gets JSON as body. So, I want to allocate ObjectWirter in @Before method like this:

@WebMvcTest(EmployeeController.class)
class EmployeeControllerTest {

public ObjectWriter ow = null;

    @Before
    public void setup(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        this.ow = mapper.writer().withDefaultPrettyPrinter();
    }

...

Then run test:

@Test
void saveEmployee() throws Exception{
   when(employeeService.save(new Employee())).thenReturn(1);

   this.mockMvc.perform(post("/api/employee").contentType(APPLICATION_JSON_UTF8)
            .content(ow.writeValueAsString(new Employee())))
            .andExpect(status().isCreated());
}

But I get java.lang.NullPointerException on ow. (IDE says: ow = null).

Actually, when I call setup() method manually everything works fine, but I don't want to keep it like this:

    @Test
    void saveEmployee() throws Exception{
        this.setup();
        when(employeeService.save(new Employee())).thenReturn(1);

        this.mockMvc.perform(post("/api/employee").contentType(APPLICATION_JSON_UTF8)
                .content(ow.writeValueAsString(new Employee())))
                .andExpect(status().isCreated());
    }

So, any ideas? :-)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source