ferronrsmith
ferronrsmith

Reputation: 1110

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().doThrow(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!

Upvotes: 4

Views: 26246

Answers (3)

Bhaskara Arani
Bhaskara Arani

Reputation: 1667

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

Upvotes: 2

mhshams
mhshams

Reputation: 16962

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.

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1502176

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.

Upvotes: 20

Related Questions