WhatAmIDoing
WhatAmIDoing

Reputation: 109

Mocking a return value for a companion object method mockito

I'm having an issue with mocking a class with a companion object using mockito. It looks similar to this

@Component
class Util { 
      companion object {
        fun generateName(job: Job) {
              return job.name + "_" + (System.currentTimeMillis()/100L).toString()
            }
    }
}

I am trying to mock this class so I can do something like this:

I mocked the utility in test file like

var util : Util.Companion = mock()

Now inside my test I want to do the following:

@Test
fun "test function"() { //(dont have the symbols, not using the work laptop, excuse the syntax error)
 whenever(util.generateName(job)).thenReturn("mystring")
}

Since our job names contain timestamps, I need this to work otherwise my unit tests won't work. Needless to say, this whenever is not working and my functions return the "correct" result when mocked, instead of the one I want provided in the return clause, otherwise during inserts I will always get nulls since I can't mock the timestamps. Please don't suggest different mocking libraries and such, there's already almost 100 tests written with mockito, so that is not an option.

Upvotes: 0

Views: 2342

Answers (1)

Nikola Despotoski
Nikola Despotoski

Reputation: 50588

You need to mock creating the companion object, which means compiler creates empty constructor of the class and use that constructor to create the companion object of that class.

You need specifically to return mocked object whenever the constructor is called, i.e new instance for that calls is created.

This doesn't play well with Mockito. I won't suggest you PowerMockito, that's like shooting yourself in the stomach.

Upvotes: 0

Related Questions