1419636215
1419636215

Reputation: 305

Mockk match overloaded function with generics

So I have 2 overloaded score functions, one of which takes a performance param of type Performance, and the other which takes a performances param, which is a List<Performance>. The former returns a double, while the latter returns a double array. (Another team owns the Scorer class, so fixing it to not overload like this isn't really doable rn; breaking changes and all).

I want to test 2 branches, one with each implementation, how can I mock these using kotlin's mockk?

The former can be mockked using ofType(Performance::class),

scorer: Scorer = mockk()
every { scorer.score(????) } returns doubleArrayOf(0.9)

What goes there?

ofType(List<Performance>::class) doesn't work because apparently that can't be done with generics.

not(ofType(CandidateFeature::class)) results in a compile-time error Type mismatch: inferred type is DoubleArray but Double was expected

How do I explicitly choose which overriden signature I'm trying to call?

Upvotes: 4

Views: 3721

Answers (2)

Joey
Joey

Reputation: 820

Try this:

every { any<Performance>() } returns doubleArrayOf(0.9)

Using any<Performance>() will cause it to know which one to mock.

Upvotes: 3

Davide
Davide

Reputation: 3472

You can use withArg

every { scorer.score(withArg<Performance> {} ) returns mockData
every { scorer.score(withArg<List<Performance>> {} ) returns mockData

Upvotes: -1

Related Questions