javaspringjunitlog4jdbunit

Error running JUnitWeb Test on Method setup


I have a Spring application, and I've created this test:

@RunWith(SpringRunner.class)
@SpringJUnitWebConfig(locations = {
        "classpath:testDatabaseContext.xml",
        "classpath:testServicesContext.xml",
        "classpath:backoffice-servlet.xml"
})
public class UserControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Before
    void setup(WebApplicationContext wac) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
..
}

but when I start the test I got this error:

rg.junit.runners.model.InvalidTestClassError: Invalid test class 'com.pastis.UserControllerTests':
  1. Method setup() should be public
  2. Method setup should have no parameters

Solution

  • Here an example:

    RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(classes = MyWebConfig.class)
    public class CustomerControllerTest {
    
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @Before
        public void setup () {
            DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
            this.mockMvc = builder.build();
        }
    
        @Test
        public void testUserController () throws Exception {
            ResultMatcher ok = MockMvcResultMatchers.status()
                                                    .isOk();
    
            MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/customers");
            this.mockMvc.perform(builder)
                        .andExpect(ok);
    
        }
    }