Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I don't think you should be normally be testing invocations of private methods.

What matters is that your inputs give the right outputs. I would normally expect the tests to be black box. i.e. you can change the implementation but the component will still give the right output given the same inputs.

If you test such things as private methods then your tests will be very sensitive to refactorings, and their function as regression tests will be limited, since you'll have to refactor the tests along with your main code refactorings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top