當然,您可以使用PowerMock只專注於該方法。例如,使用PowerMockito具體情況,你可以這樣寫測試:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceLayer.class})
public class PowerMockitoJan10Test {
private static final java.lang.String DESIRED_COUNTRY_VALUE = "USA";
@Test
public void testServiceLayerFindCountry() throws Exception {
ApiAdaptor mock = Mockito.mock(ApiAdaptor.class);
PowerMockito.whenNew(ApiAdaptor.class).withAnyArguments().thenReturn(mock);
Mockito.when(mock.getCountry(Mockito.anyString(), Mockito.anyString())).thenReturn(DESIRED_COUNTRY_VALUE);
String country = new ServiceLayer().findCountry(1);
Assert.assertEquals(DESIRED_COUNTRY_VALUE, country);
}
}
如果你使用Spring,很可能是你需要一個JUnit運行,所以你可以使用PowerMockito JUnit的規則,而 - see this example 。
編輯:這是有趣的。使用規則時,除非您將ServiceLayer.class
添加到@PrepareForTest
列表中,否則它確實無法正常工作。在撰寫本文時,我使用了最新的PowerMockito版本1.6.4。可能值得報告。在任何情況下,這是你的測試將如何與Spring工作:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("mycontext.xml")
@PrepareForTest({ApiAdaptor.class, ServiceLayer.class})
public class PowerMockitoJan10_WithRuleTest {
private static final String DESIRED_COUNTRY_VALUE = "USA";
@Rule
public PowerMockRule rule = new PowerMockRule();
@Test
public void testServiceLayerFindCountry() throws Exception {
PowerMockito.whenNew(ApiAdaptor.class).withNoArguments().thenReturn(new ApiAdaptor() {
@Override
public String getCountry(String latitude, String longitude) {
return DESIRED_COUNTRY_VALUE;
}
});
String country = new ServiceLayer().findCountry(1);
Assert.assertEquals(DESIRED_COUNTRY_VALUE, country);
}
}
或者,如果覆蓋是一個問題,你可以嘲笑ApiAdaptor
:
...
ApiAdaptor mock = PowerMockito.mock(ApiAdaptor.class);
PowerMockito.when(mock.getCountry(Mockito.anyString(), Mockito.anyString())).thenReturn(DESIRED_COUNTRY_VALUE);
PowerMockito.whenNew(ApiAdaptor.class).withNoArguments().thenReturn(mock);
...
我正在做同樣的事情,但是當我運行測試時,沒有調用stubbed方法並且完成的方法運行... :( – ishanbakshi
我的註釋配置是這樣的: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @PrepareForTes t({ServiceLayer.class}) – ishanbakshi
你是對的,它不能像切換到規則時那樣工作。但是我在註釋列表中添加了'ServiceLayer.class',它現在運行良好。 –