簡體   English   中英

模擬時 Mockito 異常

[英]Mockito Exception when mocking

當我嘗試運行以下測試時

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() 需要一個參數,它必須是“對模擬的方法調用”。 例如:when(mock.getArticles()).thenReturn(articles);

此外,出現此錯誤的原因可能是: 1. 您存根了以下任一方法: final/private/equals()/hashCode() 方法。 這些方法不能被存根/驗證。 不支持在非公共父類上聲明的模擬方法。 2. 在 when() 中,您不會在模擬上調用方法,而是在其他對象上調用方法。

在 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(DelegatingMethodAccessor) :43) 在 java.lang.reflect.Method.invoke(Method.java:498) 在 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) 在 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) )

只需用@Mock 替換@Autowired -.-

@Mock
private DocumentService documentService;

favoriteRepository Repository 應該是一個mock 對象,來自spring boot 的benfinit,你可以在這里使用@MockBean

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM