0

我有一个 Java SE 项目,我需要为“服务”类添加一个单元测试。

public class Service {

  public void solve() {
    Source<Account> accountDataSource = new Source<>("");
    while (accountDataSource.hasNext()) {
      for (Account account : accountDataSource.getData()) {
        handleAccount(account);
      }
    }
  }

  private void handleAccount(Account account) {
    Source<Hardware> hardwareDataSource = new Source<>("");
    while (hardwareDataSource.hasNext()) {
      for (Hardware hardware : hardwareDataSource.getData()) {
        // some logic
      }
    }
  }
}
public  class Source<T> {

  public Source(String url) {
    // some logic
  }

  public boolean hasNext() {
    // some logic
  }

  public List<T> getData() {
    // some logic
  }
}

我需要两次模拟对象“Source”的创建,每次方法“getData()”都会返回一个不同的列表。(对于第一个对象列表“accountList”和第二个对象列表“hardwareList”)

public class ServiceTest {

  @Test
  public void testScenario() {

    List<Account> accountList = new ArrayList<>();
    List<Hardware> hardwareList = new ArrayList<>();

    try (MockedConstruction<Source> construction = Mockito
            .mockConstruction(Source.class, (mock, context) -> {
              Mockito.when(mock.hasNext()).thenReturn(true, false);
              Mockito.when(mock.getData()).thenReturn(accountList);
            });
    ) {

      new Service().solve();

      Assertions.assertEquals(construction.constructed().size(), 2);
    }
  }
}

我试过:用 Source< Account.class>, Source< Hardware.class> 两次添加 MockedConstruction< Source> construction = Mockito 但它不起作用

有没有办法在 try 块中定义同一个类的两个不同的构造函数行为?

4

0 回答 0