Mockito 通过但代码覆盖率仍然很低

时间:2022-11-06
本文介绍了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);
 }

}

我已经使用 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 通过但代码覆盖率仍然很低的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:如何模拟超级参考(在超级类上)? 下一条:OpenGL 扩展可用于不同的 Android 设备

相关文章

最新文章