Springboot單元測試調用Service或Dao方法出現空指針異常


在正常單元測試中,我們向方法上添加@Test注解即可,但是在springboot中我們要使用類似控制器注入方法

@Autowired
    userService userService;

又或者注入Dao層方法

 @Autowired
    private YiSouMapper yiSouMapper;

  這種自動裝配的類就可能會注入失敗,報空指針異常,就是userService或yiSouMapper無法被注入,

       那么springboot就給了我們一個將junit與springboot結合起來的依賴

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

  導入這個依賴以后我們在我們的測試類上添加@RunWith和@SpringBootTest兩個注解,記住@SpringBootTes中的classes就是你自己springboot的啟動類,

       名字需要換一下。這時運行后會啟動項目環境,使用當前Spring環境進行單元測試。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EdApplication.class)
public class FenCiUtilText {
    @Autowired
    private YiSouMapper yiSouMapper;
    @Test
    public void testDemo1() {
            //代碼
    }
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM