eq()
为您的自定义对象使用匹配器,通过执行此更改,函数模拟看起来像链接:
when(Service.foo(any(), eq(new ARequest(1, "A")))).thenReturn(new AResponse(1, "passed")); when(Service.foo(any(), eq(new ARequest(2, "2A")))).thenReturn(new AResponse(2, "passed")); when(Service.foo(any(), eq(new BRequest(1, "B")))).thenReturn(new BResponse(112, "passed"));
您应该在Request
对象中指定参数并any()
从内部删除。
另一种选择是写您的答案并检查其中的类型,例如:
when(mock.foo(anyString(), anyObject())).thenAnswer( invocation -> { Object argument = invocation.getArguments()[1]; if (argument.equals(new ARequest(1, "A"))) { return new AResponse(1, "passed"); } else if (argument.equals(new ARequest(2, "2A"))) { return new AResponse(2, "passed"); } else if (argument.equals(new BRequest(1, "B"))) { return new BResponse(112, "passed"); } throw new InvalidUseOfMatchersException( String.format("Argument %s does not match", argument) ); } );