11

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

c-an
  • 3,543
  • 5
  • 35
  • 82

2 Answers2

6

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

Mieszko Koźma
  • 460
  • 4
  • 10
  • Ah, so, when relaxed is false, it will throw an Exception, otherwise if it's true, it will return a default value. I am curious, when it's false, it throws an Exception. is it used when its methods are never called? (or other cases?). And returning default values(relaxed = true) are not purposely mock, but for why and when is it used? If is not purposely mock, it doesn't seem right. And also I am curious, in this case https://stackoverflow.com/questions/73203208/how-can-i-skip-running-a-method-with-mockk-or-mockito, can I use relaxedUnitFun? how can I use it? I don't need coEvery here? – c-an Aug 05 '22 at 02:36
1

To quote their documentation:

A relaxed mock is the mock that returns some simple value for all functions. This allows you to skip specifying behavior for each case, while still stubbing things you need. For reference types, chained mocks are returned.

source

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144
  • I read that part. But could you give me more examples? I don't get it when I should use it. – c-an Aug 04 '22 at 10:13
  • I think the use-case has been better described by the other answer, but it's essentially a way to have mocks not cause an exception when unmocked fields are needed, which could happen if you only need to use parts of a mock and ignore the rest. Be careful though, as these tend to pile up and become a commodity and in 5 years some developer will curse trying to find all instances of relaxed = true to remove them for some reason... and said developer won't be happy. – Martin Marconcini Aug 04 '22 at 12:31