小编Zee*_*lal的帖子

用不同的参数模拟相同的方法

我正在使用mockito来测试我的业务服务,它使用了我想要模拟的实用程序.对于具有不同参数的实用程序,每个服务方法至少有2-3个调用.

有没有推荐的方法来使用多个when(...).thenReturn(...)相同的方法但不同的参数?

我也想在any()里面使用游行者.可能吗?

更新:示例代码.

@Test
public void myTest() {
  when(service.foo(any(), new ARequest(1, "A"))).thenReturn(new AResponse(1, "passed"));
  when(service.foo(any(), new ARequest(2, "2A"))).thenReturn(new AResponse(2, "passed"));
  when(service.foo(any(), new BRequest(1, "B"))).thenReturn(new BResponse(112, "passed"));

  c.execute();
}

public class ClassUnderTest {
  Service service = new Service();
  public void execute() {
    AResponse ar = (AResponse) service.foo("A1", new ARequest(1, "A"));
    AResponse ar2 = (AResponse) service.foo("A2", new ARequest(2, "2A"));
    BResponse br = (BResponse) service.foo("B1", new BRequest(1, "B"));
  }
}

public class Service {
  public Object foo(String firstArgument, …
Run Code Online (Sandbox Code Playgroud)

java junit unit-testing mockito

25
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×1

junit ×1

mockito ×1

unit-testing ×1