我有一个由其他对象/依赖项组成的类,如下所示:
public class One{
private RedisPool redisPool;
private static final WeakHashMap<String, Dedup<String>> CACHE = new WeakHashMap<>();
private static final ObjectMapper mapper = new ObjectMapper();
private BigQueryManager bigQueryManager;
private RedisClientManager redisClientManager;
private PubSubIntegration pubSub;
public One(RedisPool redisPool, Configuration config) {
this.redisPool = redisPool;
bigQueryManager = new BigQueryManager(config);
redisClientManager = new RedisClientManager(redisPool, config);
pubSub = new PubSubIntegration(config);
}
....
...
other methods
}我试过了:
public class OneTest{
@Mock
RedisPool redisPool;
@Mock
Configuration config;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
One one = new One(redisPool, config);
}
}但我不确定在构造函数中构造的对象是否也会被模拟,因为我在类内的其他方法中使用过这些对象。
如何模拟构造函数中构造的对象?
发布于 2020-08-31 18:10:30
我不认为你可以单独使用Mockito来实现这一点,但如果你也使用PowerMockito,你就可以做到。
This article给出了一个与您想要实现的目标非常相似的示例。
请注意,PowerMockitio将弄乱您正在收集的任何测试覆盖率统计信息。
编辑
如果这篇文章消失了,那么要点就是您需要对Test类进行略微不同的注释
@RunWith(PowerMockRunner.class)
@PrepareForTest(One.class)
public class OneTest {@PrepareForTest注释引用您需要更改行为的类-在本例中是One类。
然后告诉PowerMoncito在创建新实例时返回一个您可以控制的对象。在你的情况下
PowerMockito.whenNew(BigQueryManager.class)
.withAnyArguments().thenReturn(mockBigQueryManager);https://stackoverflow.com/questions/63668747
复制相似问题