'Is new App() a good way to test if a spring boot app context loads?
I have just taken over maintenance of an app that has this as its only test: (Yes I know)
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@RequiredArgsConstructor
@SpringBootTest(classes = App.class)
@MockBean(ElasticSearchIndexService.class)
public class AppStartTest {
@Test
public void contextLoads() {
final var app = new App();
assertNotNull("the application context should have loaded.", app);
}
}
Apart from the fact that there is no automated testing in place is this a good way to test if a Spring boot application loads its context? I would have thought that a simple
assertTrue(true); in the test would suffice, as the context should be loaded no matter what. Why would I want to create another copy of the application? (I sadly could not find anything related to this during my google searches)
There is also the fact that it has both @RunWith(SpringRunner.class) and @SpringBootTest. The test currently "runs" properly but I would expect that this leads to some unexpected behaviour does it not? I found this SO answer talking about it but it does not go into depth why (or if ever) one should use both annotations.
Lastly I already removed the @RequiredArgsConstructor because I don't really know why it is there in the first place. In my humble opinion it does not really serve a purpose.
I am not certain if this fits SO but I was rather curious as I consider myself somewhat of a beginner Spring developer and maybe the previous dev knew more than me
Solution 1:[1]
is this a good way to test if a Spring boot application loads its context?
@M.Deinum already answered this
No it isn't. You should @Autowire your App or rather ApplicationContext and check that.
but for anyone looking for a code example it would look like this:
@Autowired
ApplicationContext applicationContext;
@Test
public void contextLoads() {
assertNotNull(applicationContext);
}
This checks if the Application Context was indeed initialized.
There is also the fact that it has both @RunWith(SpringRunner.class) and @SpringBootTest.
Is a remnant of this test initially using JUnit4, where this was indeed necessary. With JUnit5, which I am using the @RunWith(SpringRunner.class) can be left out.
I still am unsure why the @RequiredArgsConstructor annotation was ever needed but the test runs with and without it so I have removed it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SirHawrk |
