mockk icon indicating copy to clipboard operation
mockk copied to clipboard

how to use mockk to mock BuildConfig.DEBUG

Open lannyf77 opened this issue 2 years ago • 3 comments

using mockk for unit test, and would like to mock the BuilConfig.DEBUG.

        io.mockk.mockkObject(BuildConfig::class) // or mockkStatic
        io.mockk.every { BuildConfig.DEBUG } returns true //<=== throws

but it throws exception

Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock

How to mock the BuildConfig.DEBUG using mockk?

lannyf77 avatar Jul 19 '22 18:07 lannyf77

Short answer: you don't.

Longer answer: https://reflectoring.io/clean-unit-tests-with-mockito/#dont-mock-value-objects-or-collections

To expand a bit: what exactly are you trying to achieve? Why can't you pass a BuildConfig object with the right value to your code rather than mocking the BuildConfig class?

I don't really think you need a mock here, and although it's a bit hard to judge without seeing your code, this really looks like a bad design smell to me.

Raibaz avatar Jul 20 '22 12:07 Raibaz

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. If you are sure that this issue is important and should not be marked as stale just ask to put an important label.

stale[bot] avatar Nov 02 '22 02:11 stale[bot]

Short answer: you don't.

Longer answer: https://reflectoring.io/clean-unit-tests-with-mockito/#dont-mock-value-objects-or-collections

To expand a bit: what exactly are you trying to achieve? Why can't you pass a BuildConfig object with the right value to your code rather than mocking the BuildConfig class?

I don't really think you need a mock here, and although it's a bit hard to judge without seeing your code, this really looks like a bad design smell to me.

While I cannot speak for the reporter, I can tell you what I'm trying to achieve (and hence how I found this issue). I have some code that behaves differently in debug and release mode and I want to test both behaviors with the unit test. Since BuildConfig is a static class, it's being accessed directly in the function under test rather than being a parameter. While doing that is possible, it will be making the production code accommodate testing code which is exactly what we want to avoid by using mocks.

BurningAXE avatar Jan 04 '24 12:01 BurningAXE