jsch mock java-mockito/powermockito

zyfwsgd6  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(564)

我试图为下面的代码编写单元测试,但遇到了困难。请帮忙。我不知道如何编写测试,尤其是关于返回void的方法,比如addidentity()和connect()。我正在使用mockito和powermockito框架。

  1. public class A {
  2. public method1() {
  3. //some code here
  4. method2();
  5. //more code here
  6. }
  7. private void method2() {
  8. JSch jsch = new JSch();
  9. Session jschSession = null;
  10. try {
  11. jsch.addIdentity("key");
  12. jschSession = jsch.getSession("userID", "somedomain", 22);
  13. //jsch code
  14. }
  15. }
  16. }

我的测试是这样的:

  1. @Test
  2. public void my_Test() throws JSchException {
  3. A test = new A();
  4. JSch mockJsch = Mockito.mock(JSch.class);
  5. whenNew(JSch.class).withNoArguments().thenReturn(mockJsch);
  6. test.method1();
  7. }
q3qa4bjr

q3qa4bjr1#

嘲笑 JSch 不会帮助您使用当前的实现,因为您使用“始终创建的新示例” JSchnew . 这样你现在就没有机会通过模拟版本的 JSch 从外面。
更好的方法是传递 JSch 作为 A . 这使您可以灵活地传递 JSch 测试时。对于运行时,您可以使用依赖注入框架(例如,spring或jakarta ee/microfile/quarkus的cdi)来获得注入的示例(在您声明一个示例之后)。
你可以重构你的类 A 如下所示:

  1. public class A {
  2. private final JSch jsch;
  3. public A (Jsch jsch) {
  4. this.jsch = jsch;
  5. }
  6. public method1() {
  7. //some code here
  8. method2();
  9. //more code here
  10. }
  11. private void method2() {
  12. com.jcraft.jsch.Session jschSession = null;
  13. try {
  14. jsch.addIdentity("key");
  15. jschSession = jsch.getSession("userID", "somedomain", 22);
  16. jschSession.setConfig("StrictHostKeyChecking", "no");
  17. jschSession.connect();
  18. Channel channel = jschSession.openChannel("sftp");
  19. channel.connect();
  20. ChannelSftp sftpObj = (ChannelSftp) channel;
  21. sftpObj.exit();
  22. jschSession.disconnect();
  23. }
  24. }
  25. }

然后你可以传递一个 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();
}

  1. 这个测试不需要使用powermock,我宁愿只使用junitmockito
展开查看全部

相关问题