問題描述
package com.fitaxis.test;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
import com.fitaxis.leaderboard.LeaderBoard;
public class LeaderBoardTests {
@Test
public void TestThatDataIsSavedToTheDatabase()
{
LeaderBoard leaderBoard = mock(LeaderBoard.class);
//doNothing().doThrow(new RuntimeException()).when(leaderBoard).saveData();
when(leaderBoard.saveData()).thenReturn(true);
boolean res = leaderBoard.saveData();
verify(leaderBoard).saveData();
Assert.assertTrue(res);
}
}
我已經使用 mockito 來模擬一個類,但是當我使用代碼覆蓋率時,它不會檢測到該方法已被調用.難道我做錯了什么?請幫忙!
I have used mockito to mock a class, but when I use code coverage it does not detect that the method as been called. Am I doing something wrong? Please help!
推薦答案
看起來你正在模擬你對生產代碼的唯一調用.
It looks like you're mocking out the only call you're making to production code.
換句話說,你的測試說:
In other words, your test says:
- 當我調用
saveData()
時,偽造結果返回 true - 現在調用
saveData()
- 是的,結果是真的!
- When I call
saveData()
, fake the result to return true - Now call
saveData()
- yay, the result was true!
據我所知,您的生產代碼根本沒有被調用.
None of your production code is being calls at all, as far as I can see.
模擬的目的是從生產類中模擬出依賴項,或者(有時,盡管我不喜歡)模擬出您實際測試的代碼將調用的生產類的一些方法.
The point of mocking is to mock out dependencies from your production class, or (sometimes, though I prefer not to) to mock out some methods of your production class that the code you're actually testing will call.
您應該可能模擬出 Leaderboard
的依賴關系,而不是 Leaderboard
本身.如果你必須模擬出saveData()
,你應該測試調用 saveData()
的方法.. 檢查它們是否保存了正確的數據,當 saveData()
返回 false 時它們是否正確運行,等等.
You should probably be mocking out the dependencies of Leaderboard
rather than Leaderboard
itself. If you must mock out saveData()
, you should be testing the methods that call saveData()
... check that they save the right data, that they act correctly when saveData()
returns false, etc.
這篇關于Mockito 通過但代碼覆蓋率仍然很低的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!