Reputation: 126
I'm trying to write Unit test for the following piece of code and having difficulty. Please help. I'm not sure how to write tests especially around methods that returns void like addIdentity() and connect(). I'm using Mockito and powerMockito framework.
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
}
}
}
and this is how my Tests looks like:
@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();
}
Upvotes: 0
Views: 6693
Reputation: 12021
Mocking JSch
won't help you with the current implementation because you use always create a new instance of JSch
with new
. This way you currently have no chance to pass the mocked version of JSch
from outside.
A better approach would be to pass an instance of JSch
as part of the constructor of A
. This gives you the flexibility to pass any instance of JSch
while testing. For runtime you can then use a dependency injection framework (e.g. Spring or CDI that is part of Jakarta EE/Microprofile/Quarkus), to get an instance injected (after you declared one).
You can refactor your class A
like the following:
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();
}
}
}
And then you can pass a mocked instance of Jsch
to your class under test (A
) and have full control over the behavior of 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();
}
There is no need to use PowerMock for this test and I would rather stick to just using JUnit and Mockito.
Upvotes: 1