开发者

Mockito's @InjectMock annotation

I'm a little confused with @RunWith(MockitoJUnitRunner.class) and @InjectMock annotations and how they are related to each other. As per my understanding by giving @Run开发者_StackOverflow社区With(MockitoJUnitRunner.class) we don't need to initialize the mock like mock(ABC.class).

On the other hand @InjectMocks injects the mock automatically with getters and setters. The documentation says:

@InjectMocks currently it only supports setter injection. If you prefer constructor injection - please contribute a patch....

What I don't understand is that when I remove @InjectMocks below I get nullpointer exception for the tests as dependency is null. Does that mean construtor based inject is supported? Or does it has something to do with @RunWith(MockitoJUnitRunner.class)

Here's the code

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
    @Mock
    private Dependency dependency;

    @InjectMocks
    private MyClass cls = new MyClass(dependency);
    //...
}

class MyClass {
    private Dependency dependency;

    MyClass(Dependency dependency) {
        this.dependency = dependency;
    }
    //...
}


As of the latest release, Mockito supports constructor injection.

See the latest javadoc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜