DirtiesContext没有在Spring单元测试中清除ApplicationContext

时间:2017-02-10 22:20:56

标签: java spring unit-testing spring-boot spring-boot-test

我有一个名为SomeBean的类和两个针对不同场景使用Stub配置的测试。我正在使用Spring Boot。

第二个测试应该在没有Exception的情况下传递,因为我没有使用stubing来抛出异常。

DirtiesContext效果不佳。如果我删除 Test2.java 中的注释代码,我会通过测试。我想通过使用与DirtiesContext类似的东西来删除不必要的subbing。

我可能遗漏了一些基本的东西。有人可以指出我做错了什么。

 @Service
 public class SomeBeanProcessor {
   @Autowired
   private BeanValidator beanValidator;  
   public ResultBean process(SomeBean sb) throws ValidationException{
       beanValidator.validateBean(sb); 
       //Do some processing and return ResultBean; 
   } 
} 

Test1.java

RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApp.class})
@WebAppConfiguration
@ContextConfiguration(classes=Test1.Test1Config.class) {
public class Test1 {
@Configuration
  static class Test1Config {
    @Bean
    public BeanValidator getSomeRequestValidator()  {
      return new BeanValidator() {
        public void validateBean(SomeBean bean) throws ValidationException {
          throw new ValidationException("Validation failed");
        }      
      };
    }
  }
  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Autowired 
  private SomeBeanProcessor aBeanProcessor;

  @Before
  public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }
  @Test
  @DirtiesContext
  public void doTestValidationErrors() throws ValidationException{
    SomeBean sb = new SomeBean(); 
    this.aBeanProcessor.process(sb);
    Assert.fail("Should throw exception");
  }    
}

Test2.java

RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApp.class})
@WebAppConfiguration
@ContextConfiguration(classes=Test2.Test2Config.class) {
public class Test2 {
  @Configuration
  static class Test2Config {
    //@Bean
    //public BeanValidator getSomeRequestValidator()  {
    //  return new BeanValidator() {
    //    public void validateBean(SomeBean bean) throws ValidationException {       //Do nothing
    //    }      
    //  };
    //}

  }
  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Autowired 
  private SomeBeanProcessor aBeanProcessor;

  @Before
  public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

  @Test
  @DirtiesContext
  public void doTestSuccess() throws ValidationException{
    SomeBean sb = new SomeBean(); 
    this.aBeanProcessor.process(sb);
  }  
}

0 个答案:

没有答案