Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockK - reinitialize mocks for each test

Tags:

mockk

I have some mocks created using: val someService = mockk<SomeService>(relaxed = true)

There are multiple tests in the file and I want the mock to be reset for each test

Is there currently a way to do this in MockK?

I know there is MockKAnnotations.init(this), but it didn't look like there was a way to set relaxed = true in the @Mock annotation

like image 715
jc12 Avatar asked Feb 20 '18 21:02

jc12


People also ask

When should I override the implementation of a mock function?

This is useful when the code under tests relies on the output of a mocked function. In that case, overriding the implementation allows us to create test cases that cover the relevant code paths. Given a function that returns a string based on the output of another function:

How do you use a mocker in testing?

You use mocker by passing it as an argument to your test function, and calling the mock and patch functions from it. Say, you want the is_windows function to return True without taking those five precious seconds. We can patch it as follows:

Why do we need to mock between test runs?

Between test runs we need mocked/spied on imports and functions to be reset so that assertions don’t fail due to stale calls (from a previous test). This is a way to mitigate what little statefulness is in the system.

What is the use of mocks in cityrepository?

Mockito allows us to create a suitable test double for the CityRepository interface and lets us define the behavior we expect from it. Applying this possibility we can create meaningful unit tests to ensure the correct behavior of the service.


2 Answers

For resetting mocks in MockK you can use clearMocks. To create relaxed mock via annotation just check @RelaxedMockK

like image 151
oleksiyp Avatar answered Oct 12 '22 01:10

oleksiyp


clearAllMocks() clears all mocks without the need of specifying them.

like image 3
Peter Westlin Avatar answered Oct 12 '22 03:10

Peter Westlin