1
public class EHI_employee {
    private String name;
    private Integer empid;

    public EHI_Employee(String name, Integer empid) {
        this.name = name;
        this.empid = empid;
    }

    public int calculatesal(int empid) {
        return empid * 3;
    }
    public void findname(int empid,String name) {
        System.out.println("Employee with "+empid+" has name "+name);
    }
}

My Test Class:

public class EHI_EmployeeTest {
    @Mock
    EHI_Employee mock;
    @Test

    public void calculatesalTest() {
       assertEquals(mock.calculatesal(2), 6);

    }}

Output Error

junit.framework.AssertionFailedError: Expected :0 Actual :6

But When I do:

public class EHI_EmployeeTest {
    @InjectMocks
    EHI_Employee mock;
    @Test

    public void calculatesalTest() {
        assertEquals(mock.calculatesal(2), 6);

    }}

Output:

:) test passed

I have read this thread: Difference between @Mock and @InjectMocks , but i dont understand this in my context, I would love if someone can explain me with my example.

When I do this , still my test is passed, but the actual method is not checked, right??

public class EHI_EmployeeTest {
    @Mock
    EHI_Employee mock;
    @Test

    public void calculatesalTest() {
        when(mock.calculatesal(234)).thenReturn(268);
        assertEquals(mock.calculatesal(234), 268);

    }}

Please explain me!

  • 1
    your goal is to test your mock? first of all, you seem to have expected and actual reversed. OK, you are mocking a call, but you also need to inform your test with what you are mocking it. But you should be testing your actual code, not a mock, otherwise the test is pointless. – Stultuske Mar 29 '19 at 10:09
  • 1
    As @Stultuske pointed out, you're missing the point. A [unit test](http://softwaretestingfundamentals.com/unit-testing/) should check that a certain part of the implementation (an unit) is working as expected. Sometimes you need to simulate the behavior of a separate entity interacting with your component, so you _mock the entity_. Your unit test is actually validating that Mokito is working as expected, and [it is](https://github.com/mockito/mockito/wiki/FAQ#what-values-do-mocks-return-by-default). P.S. here's a quick [Mockito](https://www.vogella.com/tutorials/Mockito/article.html) tutorial. – Morfic Mar 29 '19 at 11:54

0 Answers0