Spring Junit测试类中的多个配置

时间:2015-11-19 15:03:34

标签: java spring spring-mvc junit

我们正在使用带有SpringJUnit4ClassRunner注释的ContextConfiguration,例如,测试前端控制器:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FrontEndControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private FrontEndController frontEndController;

    @Before
    public void init() {
        mockMvc = MockMvcBuilders.standaloneSetup(frontEndController).build();
    }

    @Test
    public void shouldDirectToSomeView() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("someView"));
    }

    @Configuration
    public static class FrontEndControllerTestConfiguration {

        @Bean
        public FrontEndController defaultController() {
            return // init controller
        }

        @Bean
        public SomeConfigObject config() {
            return // some config
        }
    }
}

现在,我想在同一个类中添加另一个具有不同配置的测试。例如,使用失败的数据库操作注入模拟,或者使用或。

是否可以添加另一个这样的测试(我知道,不会编译):

@Test
@ContextConfiguration(/* My other configuration */)
public void shouldDoSomeOtherStuff_InvalidConfiguration() {
      // ...
} 

在Spring 4中,这是不可能的,因为ContextConfiguration只能在类前面声明为注释。春天4有这样的东西吗?你建议尝试另一种方法吗?

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案:问题是我想为每个测试获得新的模拟,我想在执行mockMvc.perform(get("/"))之前修改它们。因此,您可以使用@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)注释。这是我的代码:

@ContextConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@RunWith(SpringJUnit4ClassRunner.class)
public class FrontEndControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private FrontEndController frontEndController;

    @Autowired
    private SomeConfigObject config;

    @Before
    public void init() {
        mockMvc = MockMvcBuilders.standaloneSetup(frontEndController).build();
    }

    @Test
    public void shouldDirectToSomeView() throws Exception {
        // mock valid behaviour of config

        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("someView"));
    }

    @Test
    public void shouldNotDirectToSomeView_InvalidConfiguration() throws Exception {
        // mock invalid behaviour of config

        mockMvc.perform(get("/"))
                .andExpect(status().is5xxServerError())
    }

    @Configuration
    public static class FrontEndControllerTestConfiguration {

        @Bean
        public FrontEndController defaultController() {
            return // init controller
        }

        @Bean
        public SomeConfigObject config() {
            return mock(SomeConfigObject.class);
        }
    }
}