This is a quite difficult setup since you initialize the emailSender
before anything can be mocked, and the emailSender
is not accessible from outside.
If you want to keep Sender
as an object
and emailSender
as a private property, it would help to initialize the emailSender
not on startup, but lazily on the first call:
object Sender {
private val emailSender: EmailSender by lazy { EmailSender() }
...
}
Then you can use Mockk's mockConstructor
to mock the constructor of EmailSender
which does also takes effect for the lazily initialized property emailSender
:
@Test
fun test() {
mockkConstructor(EmailSender::class) {
every { anyConstructed<EmailSender>().send(any()) } just runs
Sender.sendMessage("x")
verify { anyConstructed<EmailSender>().send(any()) }
}
}