jeudi 28 mai 2015

MockMvc works with standaloneSetup but not with webAppContextSetup

I'm trying to test spring rest controller using MockMvc. There are two approaches to create MockMvc instance:

@WebAppConfiguration
@ContextConfiguration(classes = {WebConfig.class})
public class ControllerWebMvcTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private WebApplicationContext webAppContext;

    private MyRestController controller;

    @BeforeMethod
    public void setUp() {
        controller = new MyRestController();
        initMocks(this);
        // first approach:
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        // second approach:
        mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
        Assert.notNull(mockMvc, "mockMvc is null");
    }
}

when I use standaloneSetup approach, tests works fine. But for testing ExceptionHandler class annotated with @ControllerAdvice which handles exceptions for controller requires webAppContextSetup. When I start my tests with second approach I receive an Exception:

java.lang.IllegalArgumentException: json can not be null or empty

Aucun commentaire:

Enregistrer un commentaire