开发者

Mockito Passes but Code Coverage still low

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().do开发者_运维技巧Throw(new RuntimeException()).when(leaderBoard).saveData();

  when(leaderBoard.saveData()).thenReturn(true);

  boolean res = leaderBoard.saveData();

  verify(leaderBoard).saveData();

  Assert.assertTrue(res);
 }

}

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:

  • 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.

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.


if i understand your question correctly :

because you are mocking LeaderBoard. that means that you are not testing it.

if you want to test LeaderBoard, you should test the actual class not the mocked one.

let say you want to test class A but this class depends on B and B is a bit difficult to instantiate in testing environment(for any reason). in such cases you can mock B.

but here is your case you are mocking class A itself. that means you are not testing anything.


add runner class as MockitoJUnitRunner, please refer the below sample code

import org.mockito.junit.MockitoJUnitRunner

@RunWith(MockitoJUnitRunner.class)
public class MockitTesterClass{
    @Mock
    private TestService testServiceMock;
}

now the code coverage will increase

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜