[英]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.