24

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.

Thiagarajan Ramanathan
  • 1,035
  • 5
  • 24
  • 32
  • 7
    It's just a placeholder so that there exists *some* test method. The "test" is that startup does not throw an exception. – chrylis -cautiouslyoptimistic- Apr 17 '18 at 22:04
  • check here. Maybe a duplicate. https://stackoverflow.com/questions/49345526/should-i-test-the-main-method-of-spring-boot-application-and-how – WesternGun Jul 05 '18 at 14:08
  • Does this answer your question? [Should I test the main() method of Spring Boot Application and how?](https://stackoverflow.com/questions/49345526/should-i-test-the-main-method-of-spring-boot-application-and-how) – dbaltor Jun 05 '20 at 15:16

2 Answers2

24

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();
    }
}
Ashish Lahoti
  • 648
  • 6
  • 8
  • Can i use this to initialize class like @BeforeEach would do?? – Rômulo Sorato Oct 20 '21 at 20:29
  • @RômuloSorato Could you please provide some example for better understanding. Here we are using `@SpringBootTest`, all the test runs in Spring context. If your class is independent and have no dependencies on other classes like utility class, you can initialize using constructor in `@BeforeEach`. If your class is dependent on other classes like service, controller, dao classes, you can initialize a class using `@Autowired` or mock class using `@MockBean`. – Ashish Lahoti Mar 06 '23 at 04:28
-5

Use different runner,

if you are using SpringRunner.class, use an alternative one such as MockitoJUnitRunner.class or MockitoJunitRunner.class rather then SpringRunner.class

@Runwith(SpringRunner.class)
 @Runwith(JUnit4ClassRunner.class)
 @Runwith(MockitoJUnit4Runner.class)
 @Runwith(MockitoJUnitRunner.class)
ozinal
  • 29
  • 3