当提供某些特定属性时,如何测试spring bean引发异常?
我尝试使用AutowireCapableBeanFactory,但是在运行任何测试方法之前都会抛出Bean实例化异常。
@RunWith(SpringRunner.class)
@SpringBootTest(
properties = {
// these properties will cause an exception in getMyService
},
classes = {MySpringBootApp.class}
)
public class TestBeanInitThrowsException {
@Autowired
private AutowireCapableBeanFactory beanFactory;
@Test
public void test1() {
this.beanFactory.createBean(OtherServiceThatRequiresMyService.class);
}
}
@Configuration
public class MyConf {
@Value("${xyz}")
private Resource xyz;
@Bean public MyService getMyService(OtherBean bean) {
// use xyz to create MyService
// can throw exceptions
}
}
答案 0 :(得分:0)
您可以对配置类进行单元测试。
@RunWith(MockitoJunitRunner.class)
class ConfTest {
@InjectMocks MyConf sut;
@Mock Resource xyz;
@Test(expected = InvalidParameterException.class)
public void testInvalidResourceThrowsException() {
when(xyz.mappedName()).thenReturn("invalid"); // or something
OtherBean param = mock(OtherBean.class);
sut.getMyService(param);
}
}