繁体   English   中英

如何在 Mockito 3 中用@InjectMocks 注释的 class 的构造函数中注入最终的 class,例如 String

[英]How to inject final class such as String into constructor of class annotated with @InjectMocks in Mockito 3

我想模拟以下 class:

public class MyRunner {
    private String name;
    private User user;//not final
    public MyRunner(String name, User user) {
      this.name = name;
      this.user = user
    }
    //...something complicated in the methods
}

就像使用JMockit

@ExtendWith(MockitoExtension.class)
public class MyRunnerTest {
    @Inject
    private String name = "sth";
    @Inject
    private User user;
    @Tested
    private MyRunner tested;
}

与 Mockito 3 类似,

@ExtendWith(MockitoExtension.class)
public class MyRunnerTest {
    @Mock
    private String name;
    @Mock
    private User user;
    @InjectMocks
    private MyRunner tested;
    @Test //from JUnit5
    public void testSth() {
      //...
    }
}

问题:由于String是最终的 class,在构造过程中将name字符串注入MyRunner会失败。 收到如下错误消息:

Cannot mock/spy class java.lang.String
Mockito cannot mock/spy because :
 - final class

可以使用新关键字初始化测试的 class:

@ExtendWith(MockitoExtension.class)
public class MyRunnerTest {
    private String name = "sth";
    @Mock
    private User user;
    private MyRunner tested = new MyRunner(name, user);
    @Test //from JUnit5
    public void testSth() {
      //...
    }
}

但是,上面的解决方案并不像仅仅使用注解那样流畅

问题:如何将最终的 class注入到带有 @InjectMocks 注释的@InjectMocks中,而不是使用new关键字显式构造它?

有很多方法可以解决这个问题。 这里有3个概念上不同的:

选项1

首先,如果您真的在谈论字符串,那么可能 mocking 它没有多大意义:基本上您的示例根本不需要 mockito 。 您可以简单地:

public class UserTest {
  private final String NAME = "sampleName;

  private User tested = new User(NAME);

 ...
}

选项 2

现在,假设您在这里不是真的在谈论String class,最好的选择是通过创建 Mocks 相当简单的接口进行编程:


public class User {
    public User(Name name) {
      ...
    }

}

public interface Name {
   String getValue();
}

@ExtendsWith(MockitoExtension.class)
public class UserTest

   @Mock
   private Name name;

   @InjectMocks
   private User tested;

选项 3

If you're absolutely required to mock static class, you can do that in mockito but it requires some additional setup: basically you create a file org.mockito.plugins.MockMaker in the directory src/test/resources/mockito-extensions that will包含:

mock-maker-inline

有关更多信息,请参阅本教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM