JUnit tests for POJOs

后端 未结 17 1662
Happy的楠姐
Happy的楠姐 2021-02-02 07:56

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 gette

相关标签:
17条回答
  • 2021-02-02 08:24

    It's probably worth a simple test to make sure you've not written

    public void setX(int x) {
       x = x;
    }
    

    Although you should be coding to avoid that (by putting a final modifier on the method parameter, or similar). It also depends how you're generating your accessors, and if they could suffer from copy/paste errors etc (this will occur even in environments that try to enforce IDE usage - it just will).

    My main concern with classes containing lots of setters/getters, however, is what is the class doing ? Objects should do stuff for you, rather than just hold and return data. If these are data entity objects then the setter/getter pattern may be correct. However the better pattern is to set the data in the object, and ask the object to do stuff with it (calculate your bank balance, launch the rocket etc.) rather than return the data and let you do it yourself!

    0 讨论(0)
  • 2021-02-02 08:24

    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/

    0 讨论(0)
  • 2021-02-02 08:25

    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.

    0 讨论(0)
  • 2021-02-02 08:27

    My answer is that trivial getters and setters do not merit their own tests. If I add any code other than simple reads or writes, then I add tests.

    Of course, this is all boilerplate, so you could easily write a script that generates unit tests for your getters and setters, if you think there's any value there. Certain IDEs may allow you to define a template that creates test cases with test methods filled in for this boilerplate code (I'm thinking of IntelliJ here, but Eclipse can probably handle it too, although I haven't done anything like this in either IDE).

    0 讨论(0)
  • 2021-02-02 08:28

    Unit Test code you want to know works (for the situations tested of course). Don't unit test code you only want to be kind of sure works.

    I can't think of much I only want to be kind of sure about.

    0 讨论(0)
提交回复
热议问题