Showing posts with label test. Show all posts
Showing posts with label test. Show all posts

Wednesday, February 14, 2024

Kotlin: how to mock a static Companion method using MockK

Introduction

How do you mock a static companion method in Kotlin using MockK?

I wanted to mock this (static) method in a companion object in Kotlin in class MyClass:

  companion object {
    fun isNegativeAndFromSavingsAccount(amount: BigDecimal, accountType: accountType) = amount < BigDecimal.ZERO && accountType == AccountType.SAVINGS
  }

 Trying it with a regular 'every' like this doesn't work:

      every { MyClass.isNegativeAndFromSavingsAccount(any(), any()) } returns false

Note it does compile fine!
But when running the test, you'll get this error:

    io.mockk.MockKException: Failed matching mocking signature for left matchers: [any(), any()]
    at io.mockk.impl.recording.SignatureMatcherDetector.detect(SignatureMatcherDetector.kt:97)

Setup:

Solution

This is the way it does work:

import io.mockk.mockkObject

    mockkObject(MyClass.Companion) {
      every { MyClass.
isNegativeAndFromSavingsAccount(any(), any()) } returns false
    }

Note this did not work, got the same error:

    mockkObject(MyClass::class)
    every { MyClass.
isNegativeAndFromSavingsAccount(any(), any()) } returns false

I found several posts, but none of them gave a clear answer and/or were using some older version of MockK. E.g: https://github.com/mockk/mockk/issues/61
and this StackOverflow post.

Some more examples and variants of solutions can be found here, e.g when using @JvmStatic.

Sunday, February 21, 2010

Best of this Week Summary 15 February - 21 February 2010

  • Expected that Mozilla uses Agile everywhere, and definitely on its flagship Firefox? Think again, only recently they started to combine Agile and more traditional Waterfall as their new development model, dubbed "Lorentz".

  • Tips for hardening your Tomcat installation. Other implementation guides, not only limited to Tomcat (also for example WebLogic) tips from U.S. DOD DISA (Defense Information Systems Agency) can be found here.

  • Always interesting to at least quickly browse through: a review of the 1993 code of Doom. And more "today": the code of Doom for the iPhone reviewed.

  • Think you know Javascript? Try one of these quizes!

Wednesday, May 16, 2007

Hello World

Of course, the first post :)