'verifyNoInteractions works with mock but not with spy
Eg.
@Component open class AService {
@Autowired private lateinit var anotherService: AnotherService
...
...
fun methodCall() {
anotherService.methodCall()
}
}
@Service
open class AnotherService{
@Autowired private lateinit var aRepo: ARepo
fun methodCall() {
aRepo.something()
}
}
@WebAppConfiguration
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest(classes = [TestAppConfig::class])
open class MyTest {
@MockBean private lateinit var aRepo: ARepo
@SpyBean private lateinit var anotherService: AnotherService
@Autowired private lateinit var aservice: AService
@Before fun setUp() {
MockitoAnnotations.openMocks(this)
}
@Test
fun shouldNotInteractWithARepo() {
aservice.methodCall() // Call to Test
verifyNoInteractions(aRepo) // This works and fails as expected
//verifyNoInteractions(anotherService) // Expect to fail since there is actually a call being made on this spy but it passes.
}
aRepo does an external network call. I have mocked it at an application level. Similarly anotherService is the encapsulating service in which aRepo makes the network call. I have spied anotherService because I want to verify at times that there is no interaction with it and at times, I want its actual behavior.
In the examples shown, I have only considedred the first case of no interaction. Testing of the actual behavior with @Spy works fine.
verifyNoInteractions on the spied field(anotherService) always passes. Why is this ?. The same when I use it on the Mocked field(aRepo), it works and fails as expected.
How do I setup in a way that if anotherService.methodCall() happens, the test should fail ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
