You need to enter a test implementation (mock / stub) of Google API objects in your test code. The malicious program Guice that Google uses internally is irrelevant here.
You should make your code depend on TrafficEstimatorServiceInterface and enter it at runtime, instead of your code TrafficEstimatorServiceInterface from the AdWordsServices factory. Then, in your unit tests, you can enter a layout or stub.
See, for example, β Inversion of control containers and dependency injection patternβ by Martin Fowler.
How it will look in practice for you depends on which IoC container you use to run your application. If you used Spring Boot, it might look something like this:
// in src/main/java/MyService.java // Your service code, ie 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); } } }
Rich
source share