ElKePoN
ElKePoN

Reputation: 930

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

First time creating a unit test and I want to make sure that the POJO object is created. I know it's not the best case scenario for Unit Test but that's how I want to get started :)

I have a class called Data and there I defined called my POJO like:

private MyPOJOExample myPOJOExample;

When a new object of the Data class is created, I'm saying:

if (data.myPOJOExample!= null) {
    this.myPOJOExample= new MyPOJOExample (data.myPOJOExample);
}

and then I defined the setters and getters for the myPOJOExample class.

So In my Unit Test, I have this:

public class MyPOJOExample extends TestCase {

    @Test
    public void expectedObject() throws Exception {

        MyPOJOExample myPOJOExample = new MyPOJOExample();
    }
}

But it's saying there are no unit tests, how can I create one so it checks if the object was created? I'm using JUnit 4

Thanks

EDIT: I see in the documentation there is an option for assertNotNull([message,] object). Is that the appropriate use case for this? How would I use it in my case?

Upvotes: 2

Views: 7497

Answers (2)

Jayesh Choudhary
Jayesh Choudhary

Reputation: 798

To test any Model Class in Java using Junit & Mockito following approach can be used. In My opinion it is the best and easiest way. Here is the 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;
    }
}

Now the Test class for Pojo:

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

Upvotes: 1

ElKePoN
ElKePoN

Reputation: 930

Well I enedup discovering it was easier than expected, for the newcomers, this is how I did it:

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

Upvotes: 2

Related Questions