[英]Create a JUnit Test of a POJO class to test Object creation - Java
第一次創建單元測試,我想確保創建了 POJO object。 我知道這不是單元測試的最佳情況,但這就是我想要開始的方式:)
我有一個名為Data
的 class ,我在那里定義了我的 POJO,例如:
private MyPOJOExample myPOJOExample;
創建Data
class 的新 object 時,我是說:
if (data.myPOJOExample!= null) {
this.myPOJOExample= new MyPOJOExample (data.myPOJOExample);
}
然后我為myPOJOExample
class 定義了 setter 和 getter。
所以在我的單元測試中,我有這個:
public class MyPOJOExample extends TestCase {
@Test
public void expectedObject() throws Exception {
MyPOJOExample myPOJOExample = new MyPOJOExample();
}
}
但它說沒有單元測試,我如何創建一個以便檢查 object 是否已創建? 我正在使用 JUnit 4
謝謝
編輯:我在文檔中看到assertNotNull([message,] object)
有一個選項。 這是合適的用例嗎? 在我的情況下我將如何使用它?
好吧,我發現這比預期的要容易,對於新手來說,我就是這樣做的:
public class MyPOJOExampleTest {
@Test
public void expectedObjectCreated() throws Exception {
String Id = "123a";
MyPOJOExample myPOJOExample = new MyPOJOExample();
myPOJOExample.setId(Id);
try {
Assert.assertNotNull(myPOJOExample);
Assert.assertEquals(Id, myPOJOExample.getId());
} catch (AssertionError assertionError) {
throw assertionError;
} finally {
System.out.println("Object created: " + myPOJOExample + "\n");
}
}
}
To test any Model Class in Java using Junit & Mockito following approach can be used. 在我看來,這是最好和最簡單的方法。 這是 Pojo 類(模型)。
class Pojo {
private String a;
private String b;
//and so on
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
現在測試 Pojo 的 class:
class PojoTest {
@Test
public void testPojoClass() {
Pojo pojo = Mockito.spy(new Pojo());
pojo.getA();//All methods you need to cover
pojo.getB();
pojo.setA("A");
pojo.setB("B");
assertEquals(pojo.getA(), "A");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.