我试着为我的班级做一个模拟测试,但它不起作用。
原始类:
public class Service {
.................
@POST
...
public Message Info(@NotNull @Valid final UUID Id) throws IOException {
............
String httpLink = Config.getLink();
...
if ( ...) {
HttpURLConnection urlConnection = null;
URL url = new URL(OriginalLink);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(50000);
urlConnection.setReadTimeout(50000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
.................
String jsonobject = "..."; //data to be posted into api
.......
} else {
return new Message("No data to posted from file");
}
return new Message("successfully posted data from file");
}
}
测试类别:
@Before
public void before() {
MockitoAnnotations.initMocks(this);
URL u = PowerMockito.mock(URL.class);
String url = "url";
PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.when(u.openConnection()).thenReturn(huc);
PowerMockito.when(huc.getResponseCode()).thenReturn(200);
.....
PowerMockito.when(Config.getLink())
.thenReturn("url");
}
@Test
public void testInfo() throws IOException {
............
Message org = new Message("successfully posted data from file");
Message msg = Service.Info(uuid);
assertEquals(msg,org);
}
我尝试使用Mockito和PowerMockRunner进行模拟,但没有成功。使用PowerMockito时,我得到“java.lang.NullPointerException”
1条答案
按热度按时间unhi4e5o1#
对于您的实现,您不能模拟
HttpURLConnection
,因为它是在URL
的不可模拟示例中创建的,而该示例是在您的方法中使用new URL(OriginalLink);
创建的您必须创建带有某种工厂的URL,并将其注入到服务中,然后您可以模拟该服务以提供一个模拟的URL示例,而该模拟的URL示例必须提供一个模拟的HttpURLConnection示例。
或者,将创建到URL的连接的部分提取到一个额外的方法中,该方法获取URL并返回连接的HttpURLConnection,然后可以额外测试该方法,并模拟或窥探它,以便测试另一个方法。
比如
然后在代码中: