如何使用 mockito/powermock 模拟 Google 的地理编码 API 请求?
Posted
技术标签:
【中文标题】如何使用 mockito/powermock 模拟 Google 的地理编码 API 请求?【英文标题】:How can I mock Google's Geocoding API request using mockito/powermock? 【发布时间】:2016-06-09 02:08:28 【问题描述】:我想使用 mockito/powermock 对该方法进行单元测试:
@Service
public class GoogleApiService
private static final Logger logger = LoggerFactory.getLogger(GoogleApiService.class);
private static final String LANGUAGE = "es";
private List<AddressType> addressTypes = Arrays.asList(
AddressType.LOCALITY,
AddressType.ADMINISTRATIVE_AREA_LEVEL_2,
AddressType.ADMINISTRATIVE_AREA_LEVEL_1,
AddressType.COUNTRY
);
@Autowired
private GeoApiContext geoApiContext;
public String getLocalityFromLatLng(LatLng latLng) throws Exception
logger.debug("getLocalityFromLatLng");
GeocodingResult[] geocodingResults = GeocodingApi.newRequest(geoApiContext)
.latlng(latLng)
.await();
for (GeocodingResult geocodingResult : geocodingResults)
AddressType addressType = geocodingResult.types[0];
if (addressTypes.contains(addressType))
return geocodingResult.formattedAddress;
return StringUtils.EMPTY;
这是我尝试过的:
@PrepareForTest(GeocodingApi.class)
public class GoogleApiServiceUnitTest extends AbstractUnitTest
private static final Double LATITUDE = -38.010403;
private static final Double LONGITUDE = -57.558408;
@Mock
private GeoApiContext geoApiContext;
@InjectMocks
private GoogleApiService googleApiService;
@Test
public void testGetLocalityFromLatLng() throws Exception
LatLng latLng = new LatLng(LATITUDE, LONGITUDE);
GeocodingResult geocodingResult = new GeocodingResult();
GeocodingResult[] geocodingResults = new GeocodingResult[] geocodingResult ;
GeocodingApiRequest geocodingApiRequest = new GeocodingApiRequest(geoApiContext);
geocodingApiRequest.latlng(latLng);
mockStatic(GeocodingApi.class);
// when(GeocodingApi.newRequest(geoApiContext))
// .thenReturn(geocodingApiRequest);
// when(GeocodingApi.newRequest(geoApiContext).latlng(latLng))
// .thenReturn(geocodingApiRequest);
when(GeocodingApi.newRequest(geoApiContext).latlng(latLng).await())
.thenReturn(geocodingResults);
String locality = googleApiService.getLocalityFromLatLng(latLng);
assertThat(locality, is(notNullValue()));
verifyStatic(times(1));
GeocodingApi.newRequest(geoApiContext).latlng(latLng).await();
verifyNoMoreInteractions(geoApiContext);
我收到 NullPointerException。这是堆栈跟踪:
java.lang.NullPointerException
at com.google.maps.PendingResultBase.await(PendingResultBase.java:56)
at com.beermap.server.unit.service.GoogleApiServiceUnitTest.testGetLocalityFromLatLng(GoogleApiServiceUnitTest.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
在 await() 调用行中
编辑:这是现在的样子,它仍然无法正常工作
顺便说一句,@RunWith(PowerMockRunner.class)
在 AbstractUnitTest 中
@Test
public void testGetLocalityFromLatLng() throws Exception
LatLng latLng = new LatLng(LATITUDE, LONGITUDE);
GeocodingResult geocodingResult = new GeocodingResult();
geocodingResult.types = new AddressType[] AddressType.LOCALITY ;
geocodingResult.formattedAddress = FORMATTED_ADDRESS;
GeocodingResult[] geocodingResults = new GeocodingResult[] geocodingResult ;
GeocodingApiRequest geocodingApiRequest = mock(GeocodingApiRequest.class);
mockStatic(GeocodingApi.class);
when(geocodingApiRequest.latlng(latLng)).thenReturn(geocodingApiRequest);
when(geocodingApiRequest.await()).thenReturn(geocodingResults); // NPE here
when(GeocodingApi.newRequest(geoApiContext)).thenReturn(geocodingApiRequest);
String locality = googleApiService.getLocalityFromLatLng(latLng);
assertThat(locality, is(notNullValue()));
// verifyStatic(times(1));
// GeocodingApi.newRequest(geoApiContext).latlng(latLng).await();
// verifyNoMoreInteractions(geoApiContext);
和堆栈:
java.lang.NullPointerException
at com.google.maps.PendingResultBase.makeRequest(PendingResultBase.java:79)
at com.google.maps.PendingResultBase.await(PendingResultBase.java:55)
at com.beermap.server.unit.service.GoogleApiServiceUnitTest.testGetLocalityFromLatLng(GoogleApiServiceUnitTest.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
提前致谢
【问题讨论】:
可以添加空指针堆栈跟踪吗? 【参考方案1】:这里有几个错误,说明你对mock有误解。让我们分析一下:
一开始,我希望是复制过去的错误,你没有@RunWith(PowerMockRunner.class)
,否则你会得到另一个异常。
第二点,这条注释掉的行是正确的when(GeocodingApi.newRequest(geoApiContext)).thenReturn(geocodingApiRequest);
。当GeocodingApi
的静态方法时你想返回geocodingApiRequest
。
最后,但最重要的一点,这行是错误的:when(GeocodingApi.newRequest(geoApiContext).latlng(latLng).await()).thenReturn(geocodingResults);
这里只会模拟一个静态调用:GeocodingApi.newRequest(geoApiContext)
。
并且将返回真正对象的实例,因为您创建了一个新实例
GeocodingApiRequest geocodingApiRequest = new GeocodingApiRequest(geoApiContext);
。
latlng(latLng)
方法是从真正的对象调用的。这真的是召唤,而不是嘲笑。但在我看来,你也想嘲笑它。
那就模拟一下吧:GeocodingApiRequest geocodingApiRequest = mock(GeocodingApiRequest.class);
之后。模拟所有需要模拟的调用:
when(geocodingApiRequest.latlng(latLng)).thenReturn(geocodingApiRequest);
when(geocodingApiRequest.await()).thenReturn(geocodingResults);
另一个错误,但与以前一样重要且更明显:未为geocodingResult
设置所需文件。
GeocodingResult geocodingResult = new GeocodingResult();
geocodingResult.types = new AddressType[] AddressType.LOCALITY;
geocodingResult.formattedAddress = "Some address";
完整的工作测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest(GeocodingApi.class, GeocodingApiRequest.class)
public class GoogleApiServiceUnitTest
private static final Double LATITUDE = -38.010403;
private static final Double LONGITUDE = -57.558408;
@Mock
private GeoApiContext geoApiContext;
@InjectMocks
private GoogleApiService googleApiService;
@Test
public void testGetLocalityFromLatLng() throws Exception
LatLng latLng = new LatLng(LATITUDE, LONGITUDE);
GeocodingResult geocodingResult = new GeocodingResult();
geocodingResult.types = new AddressType[] AddressType.LOCALITY;
geocodingResult.formattedAddress = "Some address";
GeocodingResult[] geocodingResults = new GeocodingResult[] geocodingResult ;
GeocodingApiRequest geocodingApiRequest = mock(GeocodingApiRequest.class);
when(geocodingApiRequest.latlng(latLng)).thenReturn(geocodingApiRequest);
when(geocodingApiRequest.await()).thenReturn(geocodingResults);
mockStatic(GeocodingApi.class);
when(GeocodingApi.newRequest(eq(geoApiContext)))
.thenReturn(geocodingApiRequest);
String locality = googleApiService.getLocalityFromLatLng(latLng);
assertThat(locality, is(notNullValue()));
verifyStatic(times(1));
GeocodingApi.newRequest(geoApiContext);
// add verification other mock if you really need it
verifyNoMoreInteractions(geoApiContext);
【讨论】:
谢谢,它有帮助,但仍然无法正常工作,我仍然在 await() 调用中收到 NPE,我编辑了我的测试(请参阅答案中的编辑)并复制/粘贴您的解决方案,并且两者都在同一行失败。 您是否将“GeocodingApiRequest.class”添加到“@PrepareForTest”? 哦,我忘记了,但我现在添加了,但仍然无法正常工作..同样的错误 嗯,我在发布之前测试了我的代码,所以另一个猜测可能会有所不同,它使用'Mockito.mock'而不是'PowerMockito.mock'。 太棒了!这就是诀窍!非常感谢!我会为任何其他有同样问题的人更新问题。再次感谢!以上是关于如何使用 mockito/powermock 模拟 Google 的地理编码 API 请求?的主要内容,如果未能解决你的问题,请参考以下文章
模拟系统类时的 Mockito + PowerMock LinkageError
单元测试及框架简介 --junitjmockmockitopowermock的简单使用