Unable to mock the same class constructor two times with different behaviors in Junit5 Mockito-inline

60 Views Asked by At

I have a Java SE project and I need to add a unit test for the class "Service".

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
  }
}

I need to mock the creation of the object "Source" two times and each time the method "getData()" will return a different list. (for the first object the list 'accountList' and with the second object the list '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);
    }
  }
}

I tried: adding MockedConstruction< Source> construction = Mockito two times with Source< Account.class>, Source< Hardware.class> but it's not working

Is there any way to define two different constructor behaviors of the same class in the try block?

0

There are 0 best solutions below