问题描述
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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)