以前沒有接觸過springboot,因新公司需要有去簡單瞭解了下。
然後今天在寫後端代碼的時候,本能的想寫個單元測試類。於是就按照以前使用eclipse中的maven項目時所用的那種方法。結果當然並不順利,當然也應該是我技術太菜。。。
==================================
如果新建項目裏面src目錄下已經就有test目錄,那麼你就可以跳過以下步驟。如果沒有test目錄,那麼請看下面。首先新建一個test目錄,然後在test目錄下再建一個java目錄,然後鼠標放在java目錄上再右擊,找到Mark Directory as --->Test Sources Root,這樣生成的纔是測試目錄。。
=======================
接着寫測試類,要注意目錄結構,即測試類的包路徑要在SpringBoot入口類的子包中!原因的話自己看SpringBoot的HelloWorld應該是有講的比較清楚。。
=====================
以下是測試類,注意註解纔是重點。。
package com.lin.demo;
import com.lin.demo.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private UserService userService;
@Test
public void insertUser() {
System.out.print(userService.findUserById(2));
}
}
=======================
以上正常來說是可以正常使用測試類了,,然而這個是我自己建的工程,跟公司的工程目錄還是不太一樣,所以我又遇到問題了。
就是:如果springBoot的入口類那邊不是用SpringBootApplication這個註解,那麼要注意了,你很有可能跟我遇到同一個問題:
如果springBoot的入口類那邊不是用SpringBootApplication這個註解,那麼你的測試類還是會報錯
主要看這個
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
因爲SpringBootApplication是個組合註解,包含了好幾個註解,如果不是用這個註解,那麼就要寫很多個,包括下面這個,而就是因爲這個測試類也啓動不起來。。。
============================
===========================
好像說的有點亂。。
有需要請參考以下博文如何高效使用idea進行Spring boot測試?,是這篇文章給了我參考和思路。。