Created
February 5, 2019 21:43
-
-
Save postazure/d87e71e953db0c27a4dbec93d2055c2b to your computer and use it in GitHub Desktop.
Reset JUNIT5 MockBeans in BeforeEach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ResetAllMocksInContextExtension : BeforeEachCallback { | |
override fun beforeEach(context: ExtensionContext?) { | |
val testInstance = context!!.testInstance.get() | |
val testContext = getAccessibleContext(testInstance) | |
resetMocksInContext(testContext) | |
} | |
private fun getAccessibleContext(testInstance: Any): Any? { | |
// Within the test instance is a private context that we need to access, so we are setting the field as accessible on the class | |
val contextFieldDefinition = testInstance::class.java.declaredFields[0] | |
contextFieldDefinition.isAccessible = true | |
return contextFieldDefinition.get(testInstance) | |
} | |
private fun resetMocksInContext(testContext: Any?) { | |
testContext!!::class.java.declaredFields | |
.mapNotNull { fieldDefinition -> getAccessibleField(fieldDefinition, testContext) } | |
.filter { property -> isMock(property) } | |
.forEach { mock -> reset(mock) } | |
} | |
private fun getAccessibleField(fieldDefinition: Field, testContext: Any?): Any? { | |
fieldDefinition.isAccessible = true | |
return fieldDefinition.get(testContext) | |
} | |
private fun isMock(property: Any) = property::class.java.declaredFields.find { field -> field.name == "mockitoInterceptor" } != null | |
} | |
---------------------------- | |
@ExtendWith(SpringExtension::class, ResetAllMocksInContextExtension::class) | |
@SpringBootTest | |
@ActiveProfiles("test") | |
annotation class RestControllerTest | |
---------------------------- | |
@RestControllerTest | |
class ControllerTest { | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment