I have the following class.
public Task {
public static Task getInstance(String taskName) {
return new Task(taskName);
}
private Task(String taskName) {
this.taskName = taskName;
}
}
I am testing the Task.getInstance()
using JMockit. While I test, I need to verify that the call to the private Task()
was actually made. I have used the Verifications
block earlier to verify the method execution on the test fixture object, but here I don't have that.
This can be done, although it very likely shouldn't be on any properly written test:
@Test
public void badTestWhichVerifiesPrivateConstructorIsCalled()
{
new Expectations(Task.class) {{ // partially mocks `Task`
// Records an expectation on a private constructor:
newInstance(Task.class, "name");
}};
Task task = Task.getInstance("name");
assertNotNull(task);
}
@Test
public void goodTestWhichVerifiesTheNameOfANewTask()
{
String taskName = "name";
Task task = Task.getInstance(taskName);
assertNotNull(task);
assertEquals(taskName, task.getName());
}
@Test
public void goodTestWhichVerifiesANewTaskIsCreatedEverytime()
{
Task task1 = Task.getInstance("name1");
Task task2 = Task.getInstance("name2");
assertNotNull(task1);
assertNotNull(task2);
assertNotSame(task1, task2);
}
Again, both partial mocking and the mocking of private methods/constructors should be avoided in general.