[英]Mocking dependency initialized in constructor
我想模拟在构造函数中初始化的依赖关系,在我的情况下,我想模拟Kafka生产者,以便可以模拟通过kafka发送消息,我的代码如下所示:
private Producer<String, String> producer;
private int messageTimeOut;
private String topicName;
@Autowired
public classConstructor(@Value("${bootstrap.servers}") String bootstrapServers,
@Value("${topic.name}") String topicName, @Value("${message.send.timeout}") int messageTimeOut) {
this.messageTimeOut = messageTimeOut;
this.topicName = topicName;
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("key.serializer", StringSerializer.class.getName());
props.put("value.serializer", StringSerializer.class.getName());
props.put("acks", "all");
producer = new KafkaProducer<>(props);
}
任何人都可以建议如何实现这一目标。
无法模拟构造函数创建的对象。 理想情况下,创建类时,不应实例化要模拟的类。 无论如何,有几种解决方法可以实现此目的。
我想您可以使用PowerMock。 它允许在实例化时返回自定义对象。 像这样:
@RunWith(PowerMockRunner.class)
@PrepareForTest({TargetClass.class})
public class Test {
@Before
public void setUp() throws Exception {
PowerMockito.whenNew(TargetClass.class).withAnyArguments().thenReturn(/* instance with you target constructor arguments */);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.