您需要将 Google API 对象的测试实现(模拟/存根)注入到您的测试代码中。Google 内部使用的 Guice 注入与此处无关。
您应该让您的代码依赖TrafficEstimatorServiceInterface并在运行时注入它,而不是让您的代码TrafficEstimatorServiceInterface从AdWordsServices工厂获取 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);
        }
    }
}