我正在嘗試為我目前正在從事的專案撰寫一些基本的單元測驗,我的服務有一個addPlaneModel
添加平面模型的方法(在引擎蓋下,它將一個PlaneModel
實體添加到 aTreeMap
中,如果TreeMap
已經包含密鑰)。
我可以撰寫一個測驗(例如shouldAddNewPlane_Succeed
)來查看它是否正確添加,PlaneModel
但是如果我想創建一個測驗來查看是否PlaneModel
已經存在,我的問題就來了(例如shouldAddNewPlane_ThrowExistingModelException
,因為我應該呼叫addPlaneModel
兩次以使其拋出例外,但是如果shouldAddNewPlane_Succeed
測驗沒有首先運行,我真的不知道該方法是否可以正常作業。
我讀過單元測驗應該彼此獨立,但我無法真正掌握在這種情況下如何做到這一點,我是否必須按順序運行它們?
uj5u.com熱心網友回復:
您應該在每次測驗之前創建您正在測驗的類的新實體。
所以你的測驗類看起來像:
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.
}
}
uj5u.com熱心網友回復:
如果你想在運行測驗之前執行一些通用代碼,你可以使用@Before
JUnit 中的方法注解。例如:
@Before
public void init() {
LOG.info("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
此代碼將始終在您運行的任何其他測驗之前執行。這對于定義執行測驗的特定順序很有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/508590.html