Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit tests for POJOs

Tags:

java

junit

pojo

I work on a project where we have to create unit tests for all of our simple beans (POJOs). Is there any point to creating a unit test for POJOs if all they consist of is getters and setters? Is it a safe assumption to assume POJOs will work about 100% of the time?


Duplicate of - Should @Entity Pojos be tested?

See also

Is it bad practice to run tests on a DB instead of on fake repositories?

Is there a Java unit-test framework that auto-tests getters and setters?

like image 602
Ryan Thames Avatar asked Mar 23 '09 17:03

Ryan Thames


People also ask

Can we write JUnit for POJO class?

Here we will see one complete example of JUnit testing using POJO class, Business logic class, and a test class, which will be run by the test runner. Create EmployeeDetails. java in C:\>JUNIT_WORKSPACE, which is a POJO class. get/set the value of employee's name.

How do you write JUnit test cases for model classes in Java?

@RunWith(MockitoJUnitRunner. class) public class MyClassTest{ @InjectMocks MyClass myClass; @Mock MyDAO myDAO; private MyObject myObj; private List<MyObject> objList; @Before public void setUp() throws Exception { myObj = new MyObject(); myObj.


2 Answers

The rule in TDD is "Test everything that could possibly break" Can a getter break? Generally not, so I don't bother to test it. Besides, the code I do test will certainly call the getter so it will be tested.

My personal rule is that I'll write a test for any function that makes a decision, or makes more than a trivial calculation. I won't write a test for i+1, but I probably will for if (i<0)... and definitely will for (-b + Math.sqrt(b*b - 4*a*c))/(2*a).

BTW, the emphasis on POJO has a different reason behind it. We want the vast quantity of our code written into POJOs that don't depend on the environment they run in. For example, it's hard to test servlets, because they depend upon executing within a container. So we want the servlets to call POJOs that don't depend on their environment and are therefore easy to test.

like image 162
Uncle Bob Avatar answered Sep 22 '22 10:09

Uncle Bob


POJOs may also contain other functions, such as equals(), hashCode(), compareTo(), and various other functions. It may be useful to know that those functions are working correctly.

like image 34
Kevin Crowell Avatar answered Sep 23 '22 10:09

Kevin Crowell