【问题标题】:Is it possible to Mock and ignore properties是否可以模拟和忽略属性
【发布时间】:2018-12-10 13:56:52
【问题描述】:

我正在更改我们的身份策略,并且我们正在使用在将实体写入数据库之前生成的 ID。由于我们模拟某些服务调用的方式,此更改导致我们的一些测试失败。

TimeLog timeLog = buildTimeLog('123456', mockEmployeeId);
TimeLog mockTimeLog = buildTimeLog('123456', mockEmployeeId);
when(this.timeLogService.save(mockTimeLog)).thenReturn(timeLog);

当测试调用 Controller 时,Controller 中的绑定实体会获得与预期的模拟不同的 ID,因为实体会生成 ID。而在此之前,数据库生成了 ID,因此模拟工作。

如果有办法告诉 Mockito 忽略期望中的属性?这将解决问题,测试仍然有效。否则,欢迎使用其他方法。

【问题讨论】:

    标签: unit-testing spring-boot mocking mockito


    【解决方案1】:

    您不能告诉 mockito 忽略期望中的属性,因为它使用 java“equals”方法...您可以在 TimeLog 中定义一个等于 igonres ID 的方法,但我怀疑这不会给你你想要的想。另一种方法是,与其试图告诉 mockito 什么不验证,不如明确定义使用 hamcrest 匹配器验证什么。定义一个 hamcrest 匹配器,它只匹配您要验证的字段,即除了 ID 之外的所有字段。所以像:

    private class TimeLogMatcher extends TypeSafeMatcher<TimeLog> {
        private final EmployeeId employeeId;
    
        public TimeLogMatcher(EmployeeId employeeId) {
            this.employeeId = employeeId;
        }
    
        @Override
        public void describeTo(Description description) {
            description.appendText("TimeLog with employeeId=" + employeeId);
        }
    
        @Override
        public boolean matchesSafely(TimeLog item) {
            return employeeId.equals(item.getEmployeeId());
        }
    }
    

    然后,而不是调用你的“buildTimeLog”方法正在调用 mockito Matchers 类,例如:

    TimeLog timeLog = Matchers.argThat(new TimeLogMatcher(mockEmployeeId));
    

    或者,您也可以始终使用 Answer 对象:

    when(this.timeLogService.save(any(TimeLog.class)).thenAnswer(new Answer<TimeLog> {
        public TimeLog answer(InvocationOnMock invocation) throws Throwable {
            TimeLog receivedTimeLog = invocation.getArgumentAt(0, TimeLog.class);
            assertThat(receivedTimeLog.getEmployeeId(), equalTo(mockEmployeeId));
            return timeLog;
        }
    });
    

    这一切都有意义吗?

    【讨论】:

    • 非常有意义。我已经沿着这条路走,但并没有完全到达那里。这有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 2019-04-17
    • 2015-11-05
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多