Java 使用Mockito在抽象类中模拟静态方法
我正在尝试使用JUNIT和Mockito为类B method2编写单元测试 我厌倦了这样的事情:Java 使用Mockito在抽象类中模拟静态方法,java,mockito,httpurlconnection,junit5,java-11,Java,Mockito,Httpurlconnection,Junit5,Java 11,我正在尝试使用JUNIT和Mockito为类B method2编写单元测试 我厌倦了这样的事情: public abstract class A { public String method1( String urlString ) { HTTP HttpURLConnection con = getConnection(url); .... I use con.getInpurStream() to get the data and return i
public abstract class A {
public String method1( String urlString ) {
HTTP HttpURLConnection con = getConnection(url);
.... I use con.getInpurStream() to get the data and return it...
}
public HttpURLConnection getConnection(URL url) {
URL url = new URL(urlString);
return (HttpURLConnection) url.openConnection();
}
}
public class B extends A {
public String method2(String urlString) {
return method1(urlString);
}
}
我一直都是这样
来自该url而不是dummyRes的实时数据
请帮忙/\
编辑1:
删除了静态方法。我仍然无法模拟getConnection()方法来返回模拟的连接
编辑2:
将生成URL对象移动到getConnection方法,以避免生成新URL,这样我就可以对其进行模拟,并在测试中对此进行了更改。仍在采集实时值。似乎应该有这样的东西
public class testB {
String urlString = "someValid.url";
String dummyRes = "dummy Response";
InputStream res = new ByteArrayInputStream(dummyRes.getBytes());
B mockB = Mockito.mock(B.class);
HttpURLConnection connection = Mockito.mock(HttpURLConnection.class);
Mockito.when(connection.getInputStream()).thenReturn(res);
Mockito.when(mockB.getConnection(urlString)).thenRetrun(connection);
assertEquals("dummy Response", mockB.method2("someValid.url");
}
似乎应该有这样的事情
public class testB {
String urlString = "someValid.url";
String dummyRes = "dummy Response";
InputStream res = new ByteArrayInputStream(dummyRes.getBytes());
B mockB = Mockito.mock(B.class);
HttpURLConnection connection = Mockito.mock(HttpURLConnection.class);
Mockito.when(connection.getInputStream()).thenReturn(res);
Mockito.when(mockB.getConnection(urlString)).thenRetrun(connection);
assertEquals("dummy Response", mockB.method2("someValid.url");
}
静态方法不能直接模拟,对于模拟静态方法,您需要在Mockito之上使用PowerMock 另外一个选择是使用Jmockit框架。这可以用来代替使用两个框架(Mockito和PowerMock) 这里是参考,为什么静态方法的模拟不能与Mockito一起工作- [更新]:对于连接的模拟问题 而不是
Mockito.when(mockB.getConnection(tempURL)).thenRetrun(connection);
试用
Mockito.when(mockB.getConnection(any())).thenRetrun(connection);
如果您不希望传递任何,替代方法可以是模拟URL类以及方法openConnection。静态方法不能直接模拟,对于模拟静态方法,您需要在Mockito之上使用PowerMock 另外一个选择是使用Jmockit框架。这可以用来代替使用两个框架(Mockito和PowerMock) 这里是参考,为什么静态方法的模拟不能与Mockito一起工作- [更新]:对于连接的模拟问题 而不是
Mockito.when(mockB.getConnection(tempURL)).thenRetrun(connection);
试用
Mockito.when(mockB.getConnection(any())).thenRetrun(connection);
如果您不希望传递任何,可以选择模仿URL类以及方法openConnection。谢谢@Allabakash。我进行了重构,不再使用静态。但现在我只从url中获取实时数据,而不是模拟连接数据。@AnirudhGhanta,这是因为,与在父类中创建的对象相比,tempURL是不同的对象。不要传递tempURL,而是尝试在模拟时传递any(),这样可以解决问题。我也更新了答案。谢谢@Allabakash。我进行了重构,不再使用静态。但现在我只从url中获取实时数据,而不是模拟连接数据。@AnirudhGhanta,这是因为,与在父类中创建的对象相比,tempURL是不同的对象。不要传递tempURL,而是尝试在模拟时传递any(),这样可以解决问题。我也更新了答案。你在测试中模仿的
URL
实际上没有被使用。而是从提供的字符串创建一个新的URL
。这就是为什么它要进行实时连接。您在测试中模拟的URL
实际上没有被使用。而是从提供的字符串创建一个新的URL
。这就是为什么它要进行实时连接。