简体   繁体   中英

Mocking a bean that is levels down from the unit being tested

I have 2 Services

Service A

Service B

I am testing Service A. Service A gets Service B dependency injected in. Service B requires a JSoup connection, therefore I am trying to mock this Jsoup connection. The connection in Service B is handled by a Bean, ConnectionHandler, therefore I am trying to:

Create real Service A instance inject Service A instance with MockServiceB Inject MockServiceB with MockConnectionHandler (and mock the method call from in there)

Is this possible?

If you want to do a unit test, you should test Service A in isolation. To do so, you should create a mock of Service B and inject that to Service A . You should mock the complete Service B and let methods that will be invoked by Service A return the values that you need. Consequently, Service B will not need a MockConnectionHandler at all.

public class ServiceA {

  private ServiceB serviceB;

  @Inject
  public void setServiceB(ServiceB serviceB) {
    this.serviceB = serviceB;
  }

  public MonthlyStatistic createStatistics(int categoryId) {
    List<DailyStatistic> data = serviceB.fetchData(categoryId);
    return computeMonthlyStatistic(data);
  }

  private void computeMonthlyStatistic(List<DailyStatistic> data) { ... }
}
public class Service B {

  @Inject
  private Connection connection;

  public List<DailyStatistic> fetchData(int categoryId) {
    return mapToDailyStatistics(queryDb(categoryId));
  }

  private List<DailyStatistic> mapToDailyStatistics(List<Row> rows) { ... }

  private List<Row> queryDb(int categoryId) { ... }
}
@Test
public void testCreateStatistics() {
  ServiceB mockedServiceB = mock(ServiceB.class);
  when(mockedServiceB.fetchData(anyInt())).thenReturn(...);

  ServiceA serviceUnderTest = new ServiceA();
  serviceUnderTest.setServiceB(mockedServiceB);
  assertEquals(..., serviceUnderTest.createStatistics(3));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM