我正在尝试为下面的代码编写单元测试,但遇到了困难。请帮帮忙。我不确定如何编写测试,尤其是像addIdentity()和connect()这样返回空的方法。我使用的是Mockito和powerMockito框架。
public class A {
public method1() {
//some code here
method2();
//more code here
}
private void method2() {
JSch jsch = new JSch();
Session jschSession = null;
try {
jsch.addIdentity("key");
jschSession = jsch.getSession("userID", "somedomain", 22);
//jsch code
}
}
}这是我的测试的样子:
@Test
public void my_Test() throws JSchException {
A test = new A();
JSch mockJsch = Mockito.mock(JSch.class);
whenNew(JSch.class).withNoArguments().thenReturn(mockJsch);
test.method1();
}发布于 2020-12-16 15:19:48
模拟JSch对当前实现没有帮助,因为您总是使用new创建JSch的新实例。通过这种方式,您目前没有机会从外部通过JSch的模拟版本。
更好的方法是将JSch的实例作为A的构造函数的一部分进行传递。这为您提供了在测试时传递任何JSch实例的灵活性。对于运行时,您可以使用依赖注入框架(例如Spring或CDI,它是Jakarta EE/Microprofile/Quarkus的一部分),以获得注入的实例(在声明一个实例之后)。
您可以按如下方式重构您的类A:
public class A {
private final JSch jsch;
public A (Jsch jsch) {
this.jsch = jsch;
}
public method1() {
//some code here
method2();
//more code here
}
private void method2() {
com.jcraft.jsch.Session jschSession = null;
try {
jsch.addIdentity("key");
jschSession = jsch.getSession("userID", "somedomain", 22);
jschSession.setConfig("StrictHostKeyChecking", "no");
jschSession.connect();
Channel channel = jschSession.openChannel("sftp");
channel.connect();
ChannelSftp sftpObj = (ChannelSftp) channel;
sftpObj.exit();
jschSession.disconnect();
}
}
}然后,您可以将Jsch的模拟实例传递给被测类(A),并完全控制Jsch的行为
@Test
public void my_Test() throws JSchException {
JSch mockJsch = Mockito.mock(JSch.class);
A test = new A(mockJsch);
when(mockJsch.getSession("", "").thenReturn(yourSession);
test.method1();
}这个测试不需要使用PowerMock,我宁愿只使用JUnit和Mockito。
https://stackoverflow.com/questions/65316537
复制相似问题