使用 mockito 调用方法时如何检查方法参数?

How can I check method params when method call using mockito?

我正在尝试编写将测试 fillA 方法的单元测试。我需要验证 doSmth 使用正确初始化的 a 字段进行调用。 这是例子。

SecondClass secondClass = new SecondClass();

public void execute() {
  A a = new A();
  fillA(a);
  secondClass.doSmth(a);
}

private void fillA(A a) {
  a.setFirstField("first field");
  a.setSecondField("second field");
}

class SecondClass {
  public void doSmth(A a) {
    // doSmth
  }
}

class A {
  private String firstField;
  private String secondField;

  // getters and setters
}

为确保调用 secondClass,您应该使用 Mockito.verify

verify(): to check methods were called with given arguments can use flexible argument matching, for example any expression via the any() or capture what arguments where called using @Captor instead.

例如:

Mockito.verify(secondClass).doSmth(<arg>);

如果要检查 a 字段是否已正确初始化,<arg> 可以是:

  • A的一个实例(new A("first field", "second field")),如果A定义了一个合适的equals

    Arguments passed are compared using equals() method"

  • 自定义AArgumentMatcher

  • 一个ArgumentCaptor

这是您需要的测试的基本结构。您需要模拟您的 SecondClass 实例并将其注入您的 class 被测。我已将你的外部 class 命名为 Bar.

此代码假定您在 A class.

上实现了 .equals() 方法
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class BarTest {

  @Test
  public void testAIsCorrectlyInitialized() throws Exception {
    SecondClass secondClass = mock(SecondClass.class);
    Bar bar = new Bar();
    bar.setSecondClass(secondClass);

    A expected = new A();
    // here, populate "expected" with correct values

    bar.execute();

    // Verify call (assumes A implements a proper equals)
    verify(secondClass).doSmth(expected);
  }
}