java.lang.IllegalStateException Unable to find a @SpringBootConfiguration code error


insert image description here


1. Problem scenario

When using the idea-based springBoot project for unit testing, an exception occurs, as shown below:

Test ignored.

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

insert image description here

2. The reason for the error

The test class cannot find the startup class at runtime, so an error is reported

3. Solutions

① Check whether there is a startup class in the project, if not, please add it quickly

The correct startup class sample code is as follows:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//声明它为基于springboot的应用程序的启动类
@SpringBootApplication
public class springbootJpaApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(springbootJpaApplication.class,args);
    }

}

ps: The class name of the startup class can be written casually, but it is recommended to refer to the naming principle of well-known names

②If you wrote the startup class, but the package where your test class is located is not in the same root directory as the package where the startup class is located

For example: in my project, the package where the startup class is located is com.fc , while the test class is written directly under the project/test/java without a package

insert image description here

insert image description here

Solution :

1. Put the test class [the class to be unit tested] in the same directory as the startup class [such as com.fc]

insert image description here

2. If you don’t want to put the test class in the same package as the startup class, add @SpringBootTest(classes = {springbootJpaApplication.class}) to the annotation of the test class

The code example is as follows:

@SpringBootTest(classes = {
    
    springbootJpaApplication.class})
public class testJpa {
    
    

}

ps: The curly braces are the reflection of the test class you wrote yourself

You can choose one of the above two solutions, and the effect is equivalent.

insert image description here

Troubleshooting and correcting success! ! !

Guess you like

Origin blog.csdn.net/siaok/article/details/131421575