Enable deep stub(chaining methods) with Mockito


Mockito 是一个使用简单的unit test library: It enables mocks creation, verification and stubbing.


有时候在使用Mockito来mock一个类,并且stub其方法时,若是使用:

Foo mock = mock(Foo.class);

when(mock.getBar().getName()).thenReturn("NullPointerException");
我们将会得到NullPointerException,这是因为mock.getBar()将会返回null值。

这时候我们可以使用:

Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
// note that we're stubbing a chain of methods here: getBar().getName() when(mock.getBar().getName()).thenReturn("deep"); 
// note that we're chaining method calls: getBar().getName() assertEquals("deep",mock.getBar().getName());


注意应该尽量少的使用这种deep stub,这种方法应该只用在测试legancy code中。


更多资料参考:
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#3
http://mockito.googlecode.com/svn/tags/1.8.3/javadoc/org/mockito/Mockito.html#RETURNS_DEEP_STUBS

评论

此博客中的热门博文

Nu förbjuder Kina handel med elfenben

Fader av pingyins

Kineserna vill köpa Volvos kompetens