在Java对象构造函数中模拟依赖项

问题描述

我有一个由其他对象/依赖项组成的类,如下所示:

# FOR step-by-step guide of running latest zabbix version 5.0 follow these links
# https://blog.zabbix.com/zabbix-docker-containers/7150/
# https://techexpert.tips/zabbix/monitoring-docker-using-zabbix/

#it's simple just add all zabbix server IPs in zabbix host agent  conf #file like below


Server=192.168.101.11,172.1.16.1
ServerActive=192.168.101.11,172.1.16.1


if you ur using zabbix server-agent model using docker containers then while deploying containers specify zabbix server Host/Container IPs which wants to connect to zabbix agent container

Assuming if you wanna deploy zabbix server and agent in the same server running docker containers just run below docker deploy commands 


#Zabbix Server Container
sudo docker run --name zabbix-appliance -p 8080:80 -p 10051:10051 -d -h zabbix-server zabbix/zabbix-appliance

#Zabbix Agent container
sudo docker run --name=dockbix-agent-xxl   --privileged   -v /:/rootfs   -v /var/run:/var/run -p 10050:10050   -e "ZA_Server=192.168.0.3,172.17.0.1" -e "ZA_ServerActive=192.168.0.3,172.17.0.1"   -d monitoringartist/dockbix-agent-xxl-limited:latest

#Default username and password of zabbix server
#username: Admin password: zabbix
# For monitoring docker containers resources import a template from this cloned repository https://github.com/monitoringartist/zabbix-docker-monitoring

我尝试过:

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    

}

但是我不确定在构造函数内部构造的对象是否也会被嘲笑,因为我已经在类内部的其他方法中使用了这些对象。

如何模拟在构造函数内部构造的对象?

解决方法

我认为您不能仅使用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);