JUnit tests for POJOs

2019-03-17 19:57发布

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?

标签: java junit pojo
16条回答
等我变得足够好
2楼-- · 2019-03-17 20:19

This problem can be resolved by using the Lombok library which eliminates all this boilerplate code as well as the equals and hashcode.

So you don't need to test them unless you have a specific requirement for the equals and hashcode

https://projectlombok.org/

查看更多
forever°为你锁心
3楼-- · 2019-03-17 20:20

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-03-17 20:20

I once spent two hours because of something like this:

int getX()
{
    return (x);
}

int getY()
{
    return (x); // oops
}

Since it takes almost no time to write the tests for simple getters, I do it now out of habit.

查看更多
Juvenile、少年°
5楼-- · 2019-03-17 20:20

Unit tests not only validate that code works properly, but they document expected behavior. I don't know how many times I've seen things break because some time down the road, someone changes the behavior of a getter or setter in a POJO and then it unexpectedly breaks something else (for example, someone adds logic to the setter that if someone sets a null value on a string, the setter changes it to an empty string so that NPEs don't happen).

I don't look at unit tests on data store POJOs as a waste of time, I see them as a safety net for future maintenance. That being said, if you are manually writing tests to validate these objects, you are doing it the hard way. Take a look at something like http://gtcgroup.com/testutil.html

查看更多
我想做一个坏孩纸
6楼-- · 2019-03-17 20:21

There is a open source utility http://meanbean.sourceforge.net/ that allows you to test POJO's. There is a also a page that describes the merits/questions that one might have on what this utility offers and why it should be used.

I have never tired it myself (yet), but it's been recommend to me.

查看更多
手持菜刀,她持情操
7楼-- · 2019-03-17 20:26

I think if the getters and setters have been created using an IDE then it should be fine. We have other things to put our code into. Obviously, you would test the POJO's for serialization/de-serialization.

查看更多
登录 后发表回答