创建 POJO class 的 JUnit 测试以测试对象创建 - Java

Create a JUnit Test of a POJO class to test Object creation - Java

第一次创建单元测试,我想确保创建了 POJO 对象。我知道这不是单元测试的最佳案例场景,但这就是我想要开始的方式:)

我有一个名为 Data 的 class,我在那里定义了我的 POJO,如:

private MyPOJOExample myPOJOExample;

创建 Data class 的新对象时,我说:

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();
    }
}

但是它说没有单元测试,我怎样才能创建一个单元测试来检查对象是否已创建?我正在使用 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");
        }
    }
}

要使用 Junit & Mockito 测试 Java 中的任何模型 Class,可以使用以下方法。在我看来,这是最好和最简单的方法。 这是 Pojo Class(Model).

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");
    }
}