'Mock dependency being initialized with new instance inside constructor
I'm writing test for a class say Producer:
public class Producer {
ProducerConfig config;
Repo repo;
Branch branch;
.......
@Autowired
public Producer(Service, repo, branch....) {
config = new Config(service, branch);
}
}
So, the dependency in my Producer class is actually being fulfilled by another instance (service) which initialises my ProducerConfig with a new instance instead of a mock. The way I am doing is incorrect and I'm not sure if mocking a constructor would work here like I've shown in next snippet.
How do I get the same mocked ProducerConfig that is being generated in test class and assign it in the Producer constructor?
Test class:
public class ProducerTest {
@MockBean ProducerConfig config;
@MockBean Repo repo;
@MockBean Branch branch;
Producer producer;
@BeforeEach
public void init() {
Service service = Mockito.mock(Service ,class);
Mockito.doReturn(config).when(new Config(service, branch));
this.producer = new Producer(service, repo, branch);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
