Reputation: 1595
I have two solutions to test my constructor (or setters).
The first is to use getters
.
public void Test() {
Person p = new Person("toto"); // name
assertEquals("toto", p.getName());
}
The second is to use Field
class
public void Test() {
Person p = new Person("toto"); // name
final Field fieldName = p.getClass().getDeclaredField("name");
fieldName.setAccessible(true);
assertEquals("toto", fieldName.get(p));
}
What is your recommendation and why? Thank you.
Upvotes: 3
Views: 1509
Reputation: 10560
You can use the very handy library called openpojo to automatically test POJOs.
https://github.com/OpenPojo/openpojo
Upvotes: 2
Reputation: 10186
IMO, reflection should be avoided wherever possible. Of course there are some situations where it is needed, but in most situations it is not worth the large tradeoffs to performance and safety.
Secondly, and arguably more importantly, if the only way of testing a piece of code is to use reflection, then you probably don't need to test it.
Consider the following example:
public class Message {
private String message;
public Message(Message message) {
this.message = message;
}
// NO GETTERS/SETTERS
}
If I wanted to test that this constructor "works", I could write a test that uses reflection to look inside my object and checks to see if the message matches the constructor parameter. But what good is that?
Presumably, I want this message class to be consumed in some way by another piece of code. How does that code work? I will find that I probably need a getMessage()
method or something equivalent to do anything useful with the object.
In general, using reflection in unit testing is bad because it tests the underlying implementation, rather than the behaviour. Your unit tests shouldn't break when someone comes along, for example, refactors the code to store the data on a remote server.
Also, I would avoid cluttering tests with "trivial" ones like this. Focus on testing your business logic. Trust the JVM to largely work as advertised.
Upvotes: 4