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

Mockito Passes but Code Coverage still low(Mockito 通过但代码覆盖率仍然很低)
本文介绍了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 通过但代码覆盖率仍然很低的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)