您好我有一个方法,它将URL作为输入并确定它是否可访问。 下面是代码:
public static boolean isUrlAccessible(final String urlToValidate) throws WAGNetworkException {
URL url = null;
HttpURLConnection huc = null;
int responseCode = -1;
try {
url = new URL(urlToValidate);
huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
} catch (final UnknownHostException e) {
throw new WAGNetworkException(WAGConstants.INTERNET_CONNECTION_EXCEPTION);
} catch (IOException e) {
throw new WAGNetworkException(WAGConstants.INVALID_URL_EXCEPTION);
} finally {
if (huc != null) {
huc.disconnect();
}
}
return responseCode == 200;
}
我想使用PowerMockito
对isUrlAccessible()方法进行单元测试。我觉得我需要使用whenNew()
来模拟URL
的创建,并且调用when url.openConnection()
时,返回另一个模拟HttpURLConnection
对象。但我不确定如何实现这个?我是在正确的轨道上吗?任何人都可以帮我实现这个吗?
答案 0 :(得分:5)
找到解决方案。首先模拟URL类,然后模拟HttpURLConnection,当调用url.openconnection()时,返回这个模拟的HttpURLConnection对象,最后将其响应代码设置为200.继承代码:
@Test
public void function() throws Exception{
RuleEngineUtil r = new RuleEngineUtil();
URL u = PowerMockito.mock(URL.class);
String url = "http://www.sdsgle.com";
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);
assertTrue(r.isUrlAccessible(url));
}
答案 1 :(得分:1)
您可以使用
模拟新的Url实例whenNew(URL.class)..
确保从新呼叫时返回先前创建的模拟对象。
URL mockUrl = Mockito.mock(URL.class);
whenNew(URL.class).....thenReturn(mockUrl );
然后,您可以根据需要向模拟添加行为。
答案 2 :(得分:1)
URL是最终课程。要模拟最终课程,我们可以将PowerMockito与Junit结合使用。 为了模拟最终类,我们需要使用@RunWith(PowerMockRunner.class)和@PrepareForTest({URL.class})
注释测试类。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ URL.class })
public class Test {
@Test
public void test() throws Exception {
URL url = PowerMockito.mock(URL.class);
HttpURLConnection huc = Mockito.mock(HttpURLConnection.class);
PowerMockito.when(url.openConnection()).thenReturn(huc);
assertTrue(url.openConnection() instanceof HttpURLConnection);
}
}
但是在 PowerMockito.when(url.openConnection())。thenReturn(huc); 行中,抛出以下错误:
java.lang.AbstractMethodError
at java.net.URL.openConnection(URL.java:971)
at java_net_URL$openConnection.call(Unknown Source)
为了消除此错误,我们可以如下所示修改Test类:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ URL.class })
public class Test {
@Test
public void test() throws Exception {
public class UrlWrapper {
URL url;
public UrlWrapper(String spec) throws MalformedURLException {
url = new URL(spec);
}
public URLConnection openConnection() throws IOException {
return url.openConnection();
}
}
UrlWrapper url = Mockito.mock(UrlWrapper.class);
HttpURLConnection huc = Mockito.mock(HttpURLConnection.class);
PowerMockito.when(url.openConnection()).thenReturn(huc);
assertTrue(url.openConnection() instanceof HttpURLConnection);
}
}
访问:https://programmingproblemsandsolutions.blogspot.com/2019/04/abstractmethoderror-is-thrown-on.html
答案 3 :(得分:0)
为了通过mockito
库模拟java.net.URL类,您需要执行以下步骤:
mock-maker-inline
文本放入文件中。 代码:
package myproject;
import org.junit.Test;
import java.net.HttpURLConnection;
import java.net.URL;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class Test {
@Test
public void test() throws Exception {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
when(url.openConnection()).thenReturn(huc);
assertTrue(url.openConnection() instanceof HttpURLConnection);
}
}
答案 4 :(得分:0)
使用JMockit模拟API要简单得多(甚至没有模拟也要简单):
import java.io.*;
import java.net.*;
import org.junit.*;
import static org.junit.Assert.*;
import mockit.*;
public final class ExampleURLTest {
public static final class ClassUnderTest {
public static boolean isUrlAccessible(String urlToValidate) throws IOException {
HttpURLConnection huc = null;
int responseCode;
try {
URL url = new URL(urlToValidate);
huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
}
finally {
if (huc != null) {
huc.disconnect();
}
}
return responseCode == 200;
}
}
// Proper tests, no unnecessary mocking ///////////////////////////////////////
@Test
public void checkAccessibleUrl() throws Exception {
boolean accessible = ClassUnderTest.isUrlAccessible("http://google.com");
assertTrue(accessible);
}
@Test(expected = UnknownHostException.class)
public void checkInaccessibleUrl() throws Exception {
ClassUnderTest.isUrlAccessible("http://inaccessible12345.com");
}
@Test
public void checkUrlWhichReturnsUnexpectedResponseCode(
@Mocked URL anyURL, @Mocked HttpURLConnection mockConn
) throws Exception {
new Expectations() {{ mockConn.getResponseCode(); result = -1; }};
boolean accessible = ClassUnderTest.isUrlAccessible("http://invalidResource.com");
assertFalse(accessible);
}
// Lame tests with unnecessary mocking ////////////////////////////////////////
@Test
public void checkAccessibleUrl_withUnnecessaryMocking(
@Mocked URL anyURL, @Mocked HttpURLConnection mockConn
) throws Exception {
new Expectations() {{ mockConn.getResponseCode(); result = 200; }};
boolean accessible = ClassUnderTest.isUrlAccessible("http://google.com");
assertTrue(accessible);
}
@Test(expected = UnknownHostException.class)
public void checkInaccessibleUrl_withUnnecessaryMocking(
@Mocked URL anyURL, @Mocked HttpURLConnection mockConn
) throws Exception {
new Expectations() {{ mockConn.connect(); result = new UnknownHostException(); }};
ClassUnderTest.isUrlAccessible("http://inaccessible12345.com");
}
}
(在JDK 8和9上已通过JMockit 1.47验证)
答案 5 :(得分:0)
尽管该线程有一些好的建议,但是如果您中的任何一个对使用这些第三方库不感兴趣的话,这里是一个快速的解决方案。
public class MockHttpURLConnection extends HttpURLConnection {
private int responseCode;
private URL url;
private InputStream inputStream;
public MockHttpURLConnection(URL u){
super(null);
this.url=u;
}
@Override
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
@Override
public URL getURL() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
@Override
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void disconnect() {
}
@Override
public boolean usingProxy() {
return false;
}
@Override
public void connect() throws IOException {
}
}
而且,这是设置所需行为的方式
MockHttpURLConnection httpURLConnection=new MockHttpURLConnection(new URL("my_fancy_url"));
InputStream stream=new ByteArrayInputStream(json_response.getBytes());
httpURLConnection.setInputStream(stream);
httpURLConnection.setResponseCode(200);
注意:它仅模拟HttpUrlConnection
中的3种方法,如果您使用更多方法,则需要确保它们也是模拟的。