gpt4 book ai didi

java - @InjectMocks 在具有基元作为字段的类上

转载 作者:行者123 更新时间:2023-11-30 06:53:55 25 4
gpt4 key购买 nike

这是我要模拟的类(class)。

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;
}

当我使用@InjectMocks 时,它提示说它不知道如何用默认构造函数初始化它(因为没有默认构造函数)。我认为 mockito 可以使用创建它,但我不知道如何注入(inject)原语(boolean/cacheTimeToLive)。有没有办法在我的测试中做到这一点?

最佳答案

参见 Mockito documentation :

  1. Constructor injection; the biggest constructor is chosen, then arguments are resolved with mocks declared in the test only. If the object is successfully created with the constructor, then Mockito won't try the other strategies. Mockito has decided to no corrupt an object if it has a parametered constructor.
    Note: If arguments can not be found, then null is passed. If non-mockable types are wanted, then constructor injection won't happen. In these cases, you will have to satisfy dependencies yourself.

[...]

And finally, no injection will happen on the type in this case:

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 的设置方法.

关于java - @InjectMocks 在具有基元作为字段的类上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com