使用@Mock

时间:2019-03-29 10:05:24

标签: java junit mocking mockito junit5

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);
    }
}

我的测试班:

public class EHI_EmployeeTest {
    @Mock
    EHI_Employee mock;
    @Test

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

    }}

输出错误

  

junit.framework.AssertionFailedError:预期为:0实际:6

但是当我这样做时:

public class EHI_EmployeeTest {
    @InjectMocks
    EHI_Employee mock;
    @Test

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

    }}

输出

  

:)测试通过了

我已经阅读了以下线程:Difference between @Mock and @InjectMocks,但是在我的上下文中我不理解这一点,如果有人可以用我的示例向我解释,我将很乐意。

当我这样做时,仍然可以通过我的测试,但是没有检查实际方法,对吗?

public class EHI_EmployeeTest {
    @Mock
    EHI_Employee mock;
    @Test

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

    }}

请解释一下!

0 个答案:

没有答案