You have two branches to test :
- the
testObject
field references a not null object, so it is returned
- the
testObject
field references null, so you create it from the getDefaultInstance()
method.
So you could define two test methods to test each scenario and assert that the expected Test
instance is returned.
Note that generally you should not override equals()/hashCode() only to make a unit test working.
Actually if Test.getDefaultInstance()
returns at each time the same instance. You just need to compare two Test
object references.
Assert.assertSame(Object o1, Object o2)
of JUnit allowing to assert that o1==o2
is so enough :
Supposing that the class to test is Foo
:
@Test
public void getTestObject_as_null(){
Foo foo = new Foo();
Assert.assertSame(Test.getDefaultInstance(), foo.getTestObject());
}
@Test
public void getTestObject_as_not_null(){
Foo foo = new Foo();
Test test = new Test(...);
foo.setTestObject(test);
Assert.assertSame(test, foo.getTestObject());
}
It could also work with Assert.assertEquals()
but Assert.assertSame()
conveys better the intention of what we want to assert : the references.
On the contrary if Test.getDefaultInstance()
returns different instances at each invocation, you should compare the content of the returned Test
instances.
The test could look like :
@Test
public void getTestObject_as_null(){
Foo foo = new Foo();
Test expectedTest = Test.getDefaultInstance();
Test actualTest = foo.getTestObject();
Assert.assertEquals(expectedTest.getX(), actualTest.getX());
Assert.assertEquals(expectedTest.getY(), actualTest.getY());
}
And that test don't need to change as the object referenced by getTestObject()
and the expected Test object is necessary the same as you pass it as fixture :
@Test
public void getTestObject_as_not_null(){
Foo foo = new Foo();
Test test = new Test(...);
foo.setTestObject(test);
Assert.assertSame(test, foo.getTestObject());
}