javaspringspring-test

Test class in spring dosn't work properly


I would like to test my controller class. But I couldn't manage to run springBootTest class. My project written in spring boot. We are writing REST API using spring boot. When I try to excute following test class. I still get following line from terminal.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;



/*
 *
 *  @A Sabirov Jakhongir
 *
 */


@SpringBootTest
@WebMvcTest
public class PrivilegesControllerTest {

    @Autowired
    private PrivilegesController privilegesController;


    @Test
    public void add() {
        assertThat(privilegesController).isNotNull();

    }
}

enter image description here

I put here all needed dependency for testing from my project.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform-launcher -->
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.6.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>

What might be cause of not working of test Class.


Solution

  • With Junit5 and @SpringBootTest will load the full application, I had faced the same issue before, you can find details about the question here and answer here.

    The solution for this is to use your test without @SpringBootTest. The solution to your test class is as below.

    @ExtendWith(MockitoExtension.class)
    public class PrivilegesControllerTest {
    
        @InjectMocks
        private PrivilegesController privilegesController;
    
    
        @Test
        public void add() {
            assertThat(privilegesController).isNotNull();
    
        }
    }
    

    You can also use @ExtendWith(SpringExtension.class) instead of @ExtendWith(MockitoExtension.class)