0

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?

Meier
  • 3,858
  • 1
  • 17
  • 46

2 Answers2

2

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
pnzr
  • 241
  • 2
  • 3
1

Have you tried

private val mockJobRepository = mockk<JobRepository>()

?

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

Myles W
  • 63
  • 1
  • 6