![](/img/trans.png)
[英]How do I unit-test the controller of a Spring Boot application with a DataSource dependency in a @ComponentScan @Configuration
[英]About unit-test dependency
我正在嘗試為我目前正在從事的項目編寫一些基本的單元測試,我的服務有一個方法addPlaneModel
來添加平面 model (在引擎蓋下它將PlaneModel
實例添加到TreeMap
並拋出自定義如果TreeMap
已經包含鍵則異常)。
我可以編寫一個測試(例如shouldAddNewPlane_Succeed
)來查看它是否正確添加了PlaneModel
但是如果我想創建一個測試來查看PlaneModel
已經存在(例如shouldAddNewPlane_ThrowExistingModelException
因為我應該調用addPlaneModel
兩次以使其拋出例外,但如果shouldAddNewPlane_Succeed
測試沒有首先運行,我真的不知道該方法是否可以正常工作。
我讀過單元測試應該彼此獨立,但我無法真正掌握在這種情況下如何做到這一點,我是否必須按順序運行它們?
如果要在運行測試之前執行一些常用代碼,可以使用 JUnit 中的@Before
方法注解。 例如:
@Before
public void init() {
LOG.info("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
此代碼將始終在您運行的任何其他測試之前執行。 這對於定義執行測試的特定順序很有用。
您應該在每次測試之前創建您正在測試的 class 的新實例。
因此,您的測試 class 將如下所示:
class MyTests {
private MyService myService;
@Before // junit 4, or @BeforeEach for junit 5
public void setup() {
myService = new MyService(... pass mocks of dependencies ...);
}
@Test
public void aTest() {
myService...
}
@Test
public void aTest2() {
myService... // this is a fresh instance of MyService, any changes to the
// state of the instance used in aTest() are gone.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.