Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocks aren't cleared when using Junit 5's @Nested classes #12

Closed
checketts opened this issue Feb 19, 2019 · 4 comments
Closed

Mocks aren't cleared when using Junit 5's @Nested classes #12

checketts opened this issue Feb 19, 2019 · 4 comments

Comments

@checketts
Copy link

I'm super excited about leveraging @MockkBean. Thanks for creating it!

I ran into a bug where my mocks weren't being cleared when using @Nested

I was able to work around it by avoiding @Nestedclasses for testing. It appears that @MockBean had a similar problem: spring-projects/spring-boot#12470

@jnizet
Copy link
Member

jnizet commented Feb 19, 2019

Thanks for the kind words. It's indeed a Spring Boot problem.
An easy workaround with MockK is to simply reset all mocks after each test. If you don't rely on global mocks that must not be reset, this works fine. Here's what I use to do that:

import io.mockk.clearAllMocks
import org.junit.jupiter.api.extension.AfterTestExecutionCallback
import org.junit.jupiter.api.extension.ExtensionContext

/**
 * Junit extension that resets all mocks after every test execution.
 * It should not be needed because MockkBean clears the mocks that have been created in the application context by
 * default. Unfortunately, that doesn't work for nested tests due to a Spring Boot issue
 * (see https://github.com/spring-projects/spring-boot/issues/12470). So, to make things easier, we keep using this
 * extension.
 * @author JB Nizet
 */
class ClearAllMocksExtension : AfterTestExecutionCallback {
    override fun afterTestExecution(context: ExtensionContext?) {
        clearAllMocks()
    }
}

@checketts
Copy link
Author

checketts commented Feb 19, 2019

Any reason not to submit this extension to mockk or to include in springmockk itself?

@jnizet
Copy link
Member

jnizet commented Feb 20, 2019

This extension is specific to JUnit 5, and is quite easy to create, so I'm not sure MockK would create a JUnit5 module or additional dependency just to host this extension.

Adding it to SpringMockK has the same problem: I would have to add a module, or an optional dependency, just to contain this workaround for a Spring Boot bug (that doesn't work in all cases). Hopefully this bug will be fixed soon, and the workaround won't be needed anymore.

@jnizet
Copy link
Member

jnizet commented Dec 6, 2020

Fixed in Spring Boot 2.4.0 / SpringMockK 3.0.0

@jnizet jnizet closed this as completed Dec 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants