Issue
I am trying to test an event listener like this one
@Component
class EventHandler {
@EventListener
fun handler(event: SomeEvent) { //SomeEvent is has properties source and someObject
...
}
}
@SpringBootTest
class SendWelcomeEmailTest {
@Autowired
lateinit var publisher: ApplicationEventPublisher
@Test
fun test(){
val someObject = SomeObject()
val event = SomeEvent(this, someObject)
val listener = mockkClass(EventHandler::class)
publisher.publishEvent(event)
verify { listener.handler(any()) }
}
}
When I run this test I am getting an
java.lang.AssertionError: Verification failed: call 1 of 1: EventHandler(#4).handler(matcher<SomeEvent>())) was not called
error, however by using debugger I can see that handler
function is entered with correct parameters. So why doesn't verify catch the execution of handler
function?
Solution
So with springmockk:
Gradle:
testImplementation("com.ninja-squad:springmockk:3.1.1")
Maven:
<dependency> <groupId>com.ninja-squad</groupId> <artifactId>springmockk</artifactId> <version>3.1.1</version> <scope>test</scope> </dependency>
This test:
@SpringBootTest
class SendWelcomeEmailTest {
@Autowired
lateinit var publisher: ApplicationEventPublisher
@MockkBean(relaxed = true)// strict by default!
private lateinit var listenerMock: EventHandler
@Test
fun test() {
val someObject = SomeObject()
val event = SomeEvent(this, someObject)
publisher.publishEvent(event)
verify { listenerMock.handler(any()) }
}
}
..should pass!
Please also consider:
If you want to make sure Mockito (and the standard MockBean and SpyBean annotations) is not used, you can also exclude the mockito dependency:
testImplementation("org.springframework.boot:spring-boot-starter-test") { exclude(module = "mockito-core")}
...limitations, compatibility.
Answered By - xerx593
Answer Checked By - Senaida (JavaFixing Volunteer)