Reputation: 1
I recently started OOP (in Java) and was wondering if the following piece of code could validate if the constructor has been tested well, using a Junit test:
@Test
public void testConstructor() {
MyClass c1 = new myClass("Text", 1);
MyClass c2 = new myClass("Text", 1);
assertEquals(c1,c2);
}
@Test
public void testConstructor2() {
MyClass c1 = new myClass("Text", 1);
MyClass c2 = new myClass("Text", 2);
assertNotEquals(c1,c2);
}
Although it seems to be a valid check to me, I'm still a bit confused because most examples I've found about constructor testing use a .get()
method.
Any clarification would be appreciated!
Upvotes: 0
Views: 527
Reputation: 43436
If your constructor is doing really trivial things (like just setting fields), then you don't need to unit test it specifically. You won't gain much confidence in your code (since you probably had a lot anyway — it wasn't doing much that it could get wrong), and other tests that instantiate and use objects will inherently test that you didn't make trivial mistakes.
If your constructor is doing something complicated, you may be better off spinning that logic into a package-private static method and then unit testing that method by itself. If that's not reasonable (for instance, the logic sets multiple fields), then your unit tests should test the specific state you expect:
MyClass object = MyClass("Text", 1);
assertEquals("someComplicatedValue", object.getSomeField());
You shouldn't just test for object equality, since that doesn't tell you whether the fields are right, just that they're the same given identical input.
Upvotes: 2
Reputation: 1
Usually you do not put any logic in constructor except some variable initialization. Also with Dependency Injection need to keep those clean. Equals will call the equals method, so the above would not be a fare test of creation. In this case only white box testing works, like giving invalid params to constructor and such, since you have to ask what could go wrong ...
Upvotes: 0