简体   繁体   中英

Testing that bean instantiation throws an exception

How can I test that a spring bean throws an exception when some specific properties are provided?

I tried using AutowireCapableBeanFactory, but the Exception from the Bean instantiation is thrown before any of the test methods are run.

@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
    }
}

You can just unit test your configuration class.

@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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM