Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of contextLoads method in Spring Boot Junit Testcases?

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.

like image 966
Thiagarajan Ramanathan Avatar asked Apr 17 '18 21:04

Thiagarajan Ramanathan


People also ask

What is the use of @SpringBootTest?

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

What is the use of @RunWith SpringRunner class?

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

What is the purpose of the @ContextConfiguration annotation in a JUnit test?

Annotation Type ContextConfiguration. @ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.


1 Answers

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();
    }
}
like image 169
Ashish Lahoti Avatar answered Sep 22 '22 09:09

Ashish Lahoti