https://github.com/helospark/spring-context-init-fail-test
Test that the application context failed to init due the the expected reason using JUnit and Spring, for example due to BeanCreationException.
https://github.com/helospark/spring-context-init-fail-test
example failure integration-testing spring spring-boot
Last synced: 13 days ago
JSON representation
Test that the application context failed to init due the the expected reason using JUnit and Spring, for example due to BeanCreationException.
- Host: GitHub
- URL: https://github.com/helospark/spring-context-init-fail-test
- Owner: helospark
- Created: 2017-10-29T18:41:05.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2025-08-30T05:48:06.000Z (5 months ago)
- Last Synced: 2025-08-30T07:20:06.872Z (5 months ago)
- Topics: example, failure, integration-testing, spring, spring-boot
- Language: Java
- Size: 11.7 KB
- Stars: 5
- Watchers: 1
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.adoc
Awesome Lists containing this project
README
= Testing expected exception on Spring startup
Test that the application context failed to init due the the expected reason using JUnit and Spring, for example due to BeanCreationException.
== Problem
When writing full Spring (or Spring Boot) integration tests, you may want to test that the application didn't start.
Unfortunately JUnit fails as soon as the application context throws an exception not even running the test, so it cannot be tested.
Trivial solution is to move the application initializing inside a `@Test` method by manually calling the `main()` or starting via creating the Spring context manually.
These solutions are far from ideal, for one, the test annotations are not processed (ex. @SpringBootTest, @ActiveProfile, etc.), also you are rewriting the logic already in Spring.
I have attempted to create some solutions to address these problems here.
All of the extends the original Spring Junit runner to add more functionality.
== Solutions
=== JUnit 4 (Vintage)
- `ContextFailsUsingAnnotationTest`: Using just an annotation to see what exception happened
- `ContextFailsUsingInspectorTest`: Same as the previous, but using an inspector
- `ContextFailsUsingExpectedExceptionTest`: ClassRule ExpectedException to expect for exceptions in @BeforeClass
=== JUnit 5 (Jupiter)
- `ContextFailsUsingValidatorTest`: Using AssertJ to validate anything about that exception
== Limitations
You need at least an empty `@Test` method, otherwise Junit and Spring will not try to build the context.