用@spy模拟真实对象的部分行为

1.说明在某些情况下,我们需要使用一个真实对象。但是,我们同时需要自定义该对象的部分行 

为,此时用@spy 就可以帮我们达到这个目的。

2.用法:

categoryService = PowerMockito.spy(categoryService);

categoryService = Mockito.spy(CategoryService.class);

Foo mock = mock(Foo.class);
//Be sure the real implementation is 'safe'.
//If real implementation throws exceptions or depends on specific
state of the object then you're in trouble.
when(mock.someMethod()).thenCallRealMethod();

3.注:使用thenCallRealMethod 时,需要注意真实的实现部分是安全的,否则将会带来麻烦。

注意 Mock和spy用法的区别在于:当测试用例中需要使用某个对象的真实方法更多些时,
请使用spy,反之请使用Mock.

原文地址:https://www.cnblogs.com/nizuimeiabc1/p/6483055.html