MockK: mocking an jpa repository.save call

2.6k views Asked by At

My code saves an object to database in some bigger method, but I don't need to test this. So I want to mock the Repository.save method. But the save method returns the saved object. I tried the following:

@MockK
private lateinit var mockJobRepository: JobRepository
val jobSlot = slot<Job>()
// ...
every { mockJobRepository.save<Job>(capture(jobSlot)) } 
    returns(jobSlot.captured)

But it throws an runtime error: "lateinit property captured has not been initialized"

How do I just return the given argument in the mock?

2

There are 2 answers

0
Myles W On

Have you tried

private val mockJobRepository = mockk<JobRepository>()

?

I've notice @Mockk annotations on lateinit vars can be finicky

0
pnzr On

When using annotations, you have to tell Mockk at some point to initialize the annotated properties. Assuming you're using JUnit 5, you can do it by initializing mocks in @BeforeEach:

class Test {

    @MockK
    private lateinit var emailService: EmailService

    @BeforeEach
    fun setUp() {
      MockKAnnotations.init(this)
    }
}

...or just use the Mockk-Extension for JUnit:

@ExtendWith(MockKExtension::class)
class Test {
        @MockK
        private lateinit var emailService: EmailService
}

Btw. less verbose option than capturing the argument would be returnsArgument:

every { mockJobRepository.save<Job>(any()) } returnsArgument 0