模拟时发生java Mockito异常
当我尝试运行以下测试时
public class FavoriteServiceTest extends AbstractCoreTest {
@Autowired
private FavoriteRepository favoriteRepository;
@Autowired
private RevisionService revisionService;
@Autowired
private FavoriteService favoriteService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(revisionService.getGlobalRevisionNumber()).thenReturn(1L);
}
@Test
public void loadFavorites() throws Exception {
when(favoriteRepository.findFavoritesByUserId("123")).thenReturn(Collections.emptyList());
List<Favorite> favorites = favoriteService.loadFavorites(123L);
assertThat(favorites.size(), is(0));
}
我得到了以下异常,但我非常确定模拟是正确的
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported. 2. inside when() you don't call method on mock but on some other object.
at FavoriteServiceTest.setUp(FavoriteServiceTest.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
# 1 楼答案
只需将@Autowired替换为@Mock-。-
# 2 楼答案
你的
favoriteRepository
应该是一个模拟对象,从spring boot开始,你可以在这里使用@MockBean