使用Mockito测试Model类equals()方法



如何测试Model类的equals()方法。我一直遇到以下问题:

 <<< FAILURE! - in EmployeeTest
testEquals(EmployeeTest)  Time elapsed: <<< ERROR!
org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:
-> at EmployeeTest.testEquals(EmployeeTest.java:20)
Example of correct verification:
    verify(mock).doSomething()
Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
Sample test method. Using Mockito.verify() for testing equals method.  

如果您想测试equals方法,我建议您使用类似Equalsverifier的库,而不是使用mock。

正如错误消息中所说

final/private/equals((/hashCode((方法。这些方法不能存根/已验证。

因此,您必须创建真实的测试对象(而不是mock(,然后通过将其与真实的预期对象进行比较来验证equals()

或者,您可以在mock上验证其他方法(即验证姓氏是否正确设置为verify(employee).setLastName("ExpectedLastName")(。

Mockito.verify((给出了上述问题。

private static Employee mockedEmployee;
private static Employee employee;
@BeforeClass
public static void setup() {
    mockedEmployee = mock(Employee.class);
    employee = new Employee("first", "last");
    when(mockedEmployee .getFirstName()).thenReturn(Employee.getFirstName());
}
@Test
public void testEquals() {
    Mockito.verify(mockedEmployee).equals(employee);
}

相关内容

  • 没有找到相关文章

最新更新