2

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

第二个测试应该在没有异常的情况下通过,因为我没有为抛出异常所做的存根。

DirtiesContext也不能正常工作。如果我删除Test2.java中的注释代码,我可以通过测试。我想通过使用类似于DirtiesContext.

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

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

测试1.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);
  }  
}
4

0 回答 0