fer*_*ith 1 java mocking mockito
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用mockito来模拟一个类,但是当我使用代码覆盖时,它没有检测到该方法被调用.难道我做错了什么?请帮忙!
Jon*_*eet 11
看起来你正在嘲笑你对生产代码进行的唯一调用.
换句话说,你的测试说:
saveData()
,假冒结果返回truesaveData()
- 耶,结果是真的!根据我的意见,你的生产代码都没有被调用.
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.
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.
如果我正确理解你的问题:
因为你在嘲笑排行榜。这意味着你没有测试它。
如果你想测试排行榜,你应该测试实际的类而不是模拟的类。
假设您想测试 A 类,但该类依赖于 B,而 B 在测试环境中实例化有点困难(出于任何原因)。在这种情况下,您可以模拟 B。
但这是你在嘲笑 A 类本身的情况。这意味着你没有测试任何东西。