8

我想测试连接到 AdWords API 的代码,而无需实际调用 Google(这需要花钱;))。知道如何插入 TrafficEstimatorServiceInterface 的新实现吗?

AdWords Client API 使用 Guice 进行依赖注入,但我不确定如何获取 Injector 以对其进行修改?!

如果它有帮助,这就是我现在实现它的方式:

AdWordsServices adWordsServices = new AdWordsServices();
AdWordsSession session = AdwordsUtils.getSession();

TrafficEstimatorServiceInterface trafficEstimatorService =
    adWordsServices.get(session, TrafficEstimatorServiceInterface.class);
4

2 回答 2

0

为此,您应该使用测试帐户。此外,从 2013 年 3 月 1 日起,使用 AdWords API将不再收费,但您在开发工具时仍应继续使用测试帐户。

于 2013-02-26T23:06:58.470 回答
0

您需要将 Google API 对象的测试实现(模拟/存根)注入到您的测试代码中。Google 内部使用的 Guice 注入与此处无关。

您应该让您的代码依赖TrafficEstimatorServiceInterface并在运行时注入它,而不是让您的代码TrafficEstimatorServiceInterfaceAdWordsServices工厂获取 a。然后,在您的单元测试中,您可以注入一个模拟或存根。

例如,参见 Martin Fowler 的“ Inversion of Control Containers and the Dependency Injection pattern ”。

这在实践中的表现取决于您用于运行应用程序的 IoC 容器。如果您使用的是 Spring Boot,这可能看起来像这样:

// in src/main/java/MyService.java
// Your service code, i.e. the System Under Test in this discussion
@Service
class MyService {
  private final TrafficEstimatorServiceInterface googleService;

  @Autowired
  public MyService (TrafficEstimatorServiceInterface googleService) {
    this.googleService = googleService;
  }

  // The business logic code:
  public int calculateStuff() {
    googleService.doSomething();
  }
}

// in src/main/java/config/GoogleAdsProviders.java
// Your configuration code which provides the real Google API to your app
@Configuration
class GoogleAdsProviders {
  @Bean
  public TrafficEstimatorServiceInterface getTrafficEstimatorServiceInterface() {
    AdWordsServices adWordsServices = new AdWordsServices();
    AdWordsSession session = AdwordsUtils.getSession();

    return adWordsServices.get(session, TrafficEstimatorServiceInterface.class);
  }
}

// in src/test/java/MyServiceTest.java
// A test of MyService which uses a mock TrafficEstimatorServiceInterface
// This avoids calling the Google APIs at test time
@RunWith(SpringRunner.class)
@SpringBootTest
class MyServiceTest {

    @Autowired
    TrafficEstimatorServiceInterface mockGoogleService;

    @Autowired
    MyService myService;

    @Test
    public void testCalculateStuff() {
       Mockito.when(mockGoogleService.doSomething()).thenReturn(42);

       assertThat(myService.calculateStuff()).isEqualTo(42);
    }

    @TestConfiguration
    public static class TestConfig {
        @Bean()
        public TrafficEstimatorServiceInterface getMockGoogleService() {
            return Mockito.mock(TrafficEstimatorServiceInterface.class);
        }
    }
}
于 2017-11-24T09:55:34.500 回答