1. 程式人生 > 其它 >Junit測試報錯java.lang.NullPointerException空指標,以及mybatis-plus報空指標異常

Junit測試報錯java.lang.NullPointerException空指標,以及mybatis-plus報空指標異常

技術標籤:異常解決

首先應該是註解沒有加上的問題,普通的測試類是無法獲取bean的,所以才會報空指標。需要讓這個測試類執行在spring測試環境中,新增以下注釋:

@RunWith(SpringJUnit4ClassRunner.class)

我在測試mybatis-plus時,如果用了普通的juitTest,也是無法獲取bean的,故也會報出空指標異常,我的解決辦法是:
1.先匯入spring-boot-staarter-test的依賴
2.然後
在類上用@SpringBootTest
方法上用 @Test(注意匯入的是"import org.junit.jupiter.api.Test"這個包;)


```xml
        <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>

```java
import org.junit.jupiter.api.Test 用在Spring Boot 2.2.X以後
import org.junit.Test用在2.2.x之前

@