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() 时,伪造结果返回 truesaveData() - 是的,结果是真的!saveData(), fake the result to return truesaveData() - 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模板网!
如何在 JTextPane 中的组件周围环绕文本?How to wrap text around components in a JTextPane?(如何在 JTextPane 中的组件周围环绕文本?)
MyBatis,如何获取插入的自动生成密钥?[MySql]MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何获取插入的自动生成密钥?[MySql])
在 Java 中插入 Oracle 嵌套表Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java:如何将 CLOB 插入 oracle 数据库Java: How to insert CLOB into oracle database(Java:如何将 CLOB 插入 oracle 数据库)
为什么 Spring-data-jdbc 不保存我的 Car 对象?Why does Spring-data-jdbc not save my Car object?(为什么 Spring-data-jdbc 不保存我的 Car 对象?)
使用线程逐块处理文件Use threading to process file chunk by chunk(使用线程逐块处理文件)