This method is empty in all my JUnit test cases. What is the use of this method?
Sonarqube is complaining
"Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation."
I can bypass this by adding some comment but I just want to know why it is necessary.
@SpringBootTest is a very convenient method to set up an application context for tests that is very close the one we'll have in production. There are a lot of options to customize this application context, but they should be used with care since we want our tests to run as close to production as possible.
@RunWith(SpringRunner. class) provides a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in our JUnit tests, this annotation will be required.
Annotation Type ContextConfiguration. @ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.
When you build a Spring boot application using Spring Initializer. It auto creates a test class for you with contextLoads
empty method.
@SpringBootTest
class ApplicationContextTest {
@Test
void contextLoads() {
}
}
Note the use of @SpringBootTest
annotation which tells Spring Boot to look for a main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context. Empty contextLoads()
is a test to verify if the application is able to load Spring context successfully or not.
If sonarqube is complaining about the empty method then you can do something like this to verify your controller or service bean context:-
@SpringBootTest
public class ApplicationContextTest {
@Autowired
private MyController myController;
@Autowired
private MyService myService;
@Test
public void contextLoads() throws Exception {
assertThat(myController).isNotNull();
assertThat(myService).isNotNull();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With