简体   繁体   中英

Mocking dependency initialized in constructor

I want to mock the dependency initialized in constructor, in my case I want to mock Kafka producer so that I can mock the sending of message over kafka, my code looks like below:

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

Can anyone please suggest how this can be achieved.

There is no way to mock the object created by the constructor. Ideally when you create a class, you should not instantiate the class you want to mock. Anyway there are several workarounds to achive this.

  1. Pass the KafkaProducer as a parameter in constructor.
  2. Add a setKafkaProducer method to use for only unit test, and set the mock object into the class.
  3. Use Reflection to set the private field http://www.java2s.com/Code/Java/Reflection/Setprivatefieldvalue.htm

I guess you can use PowerMock. It allows to return a custom object on instantiation. Something like this:

@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 */);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM