ishallwin
ishallwin

Reputation: 310

JUnit5 mocking a class inside mocked class

I have a following situation :

Class A (test)
    .
    -> Autowired B 
           .
           -> Autowired C

A.method {
    b.method2();
}

B.method2 {
    c.method3();
}

Now I have to test A.method() ->

@InjectsMock 
A a;

@Mock
B b;

a.method();

when b.method2() is called, it obviously doesn't do anything but I actually want it to go inside b.method2() to eventually call c.method3(). Now c.method3() is what I'd want to use Mockito.when(c.method3()).return(1);

Is this possible? If so, how do I achieve this?

Upvotes: 0

Views: 124

Answers (1)

leandro.dev
leandro.dev

Reputation: 365

When using unit testing, you should think that the only piece of software that is running is this method. The objective is to isolate a part to analyze the behavior.

To test any class, a developer must make sure that the class's dependencies will not interfere with his unit tests.

Think about this situation: you call a real b.method2 and it throws an exception you don't expect. How to evaluate this case if your objective was to test this a.method?

Unit tests verify the behavior of the units. Think of a class as being a unit. Classes most often have external dependencies. Tests for such classes should not use their actual dependencies because if the dependencies are faulty, the tests will fail, even though the code inside the class may be perfectly fine.

Upvotes: 2

Related Questions