这是我试图嘲笑的班级。
private MemcachedClient memcachedClient;
private CachedObjectFactory cachedObjectFactory;
private int cacheTimeToLive;
private boolean hasCert;
@Autowired
public MyClass(CachedObjectFactory cachedObjectFactory,
MemcachedClient memcachedClient,
@Value("${cache.ttl.in.second}") int cacheTimeToLive,
@Value("${hasCert}") boolean hasCert) {
this.cachedObjectFactory = cachedObjectFactory;
this.memcachedClient = memcachedClient;
this.cacheTimeToLive = cacheTimeToLive;
this.hasCert = hasCert;
}
Run Code Online (Sandbox Code Playgroud)
当我使用 时@InjectMocks,它抱怨它无法弄清楚如何使用默认构造函数初始化它(因为没有一个)。我认为 mockito 可以使用 create this,但我不知道如何注入原语(boolean/cacheTimeToLive)。有没有办法在我的测试中做到这一点?
请参阅Mockito 文档:
- 构造函数注入;选择最大的构造函数,然后使用仅在测试中声明的模拟来解析参数。如果使用构造函数成功创建了对象,则Mockito 不会尝试其他策略。Mockito 决定不破坏具有参数构造函数的对象。
注意:如果找不到参数,则传递 null。如果需要不可模拟的类型,则不会发生构造函数注入。在这些情况下,您必须自己满足依赖项。[...]
最后,在这种情况下,类型不会发生注入:
Run Code Online (Sandbox Code Playgroud)public class ArticleManager { private ArticleDatabase database; private ArticleCalculator calculator; ArticleManager(ArticleObserver observer, boolean flag) { // observer is not declared in the test above. // flag is not mockable anyway } }
您必须自己满足依赖关系,例如使用 JUnit 的@Before.