José Escorche
José Escorche

Reputation: 33

How to do useful tests with JUnit and dependency injection?

Let's suppose we have a Java class like this:

class MyClass {
    private final DependencyA da;
    private final DependencyB db;

    public MyClass(DependencyA da, DependencyB db) {
        this.da = da;
        this.db = db;
    }

    public String foo() {
        ResultA resultA = da.someMethodA();
        ResultB resultB = db.someMethodB(resultA);
 
        return resultB.id;
    }
}

How should I do the unit test for foo method? I've read on internet that I should mock the dependencies (in this case with Mockito):

// imports...

@RunWith(MockitoJUnitRunner.class)
class MyClassTest {
    @Mock DependencyA da;
    @Mock DependencyB db;
    @InjectMocks MyClass myClass;

    @Test
    void foo() {
        when(da.someMethodA()).thenReturn(new ResultA());
        when(db.someMethodB(any(ResultA.class)).thenReturn(new ResultB());

        ResultB resultB = myClass.foo();

        assertNotNull(resultB);
    }
}

But I feel that it's a useless test because I'm mocking the whole foo method. Should I do an integration test instead?

Upvotes: 0

Views: 140

Answers (1)

Pedro Luiz
Pedro Luiz

Reputation: 331

It really depends on some things, if you want to test how the behavior of the foo method is given a certain input you are fine with that unit test.

But if you want to test the actual behavior of those dependencies methods, you could be looking to integration tests, let’s say one of those methods make some I/O operation.

Not saying that for these cases you couldn’t be doing unit tests as well, but if you are willing to not only mock those behaviors, consider these things…

Upvotes: 1

Related Questions