Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does relaxed = true do in mockK?

I read document, but I don't still get it.

The differences between this

private val myClass: MyClass = mockk(relaxed = true)

and this.

private val myClass: MyClass = mockk()

What I understood is if relaxed is true. Then, all the member fields or methods will return default values. Otherwise, not. is that correct understanding?

If so, setting always relaxed = true is better. But In this video, Ryan uses both. why?

https://youtu.be/60KFJTb_HwU?t=1015

like image 536
c-an Avatar asked Sep 13 '25 23:09

c-an


1 Answers

If you're trying to call a mock method that doesn't know what to return and relaxed is not set to true you'll get an exception thrown. This is made, so tests are less likely to introduce unpredictable behavior, due to the default values returned by methods that the developer does not purposely mock.

In the linked video the view methods are probably never called, therefore no "relaxed" is necessary. You can also use "relaxedUnitFun", which works only for methods returning Unit, handy for example for classes responsible for events logging.

This is a double-edged weapon though, as "relaxing" everything deprives you of the security mechanism mentioned above. If this is what you want, you can also configure this globally, check https://mockk.io/#settings-file

like image 88
Mieszko Koźma Avatar answered Sep 15 '25 14:09

Mieszko Koźma