Skip to content

Commit f765a31

Browse files
committed
Use instance creators only from single test file.
This ensures that ordering of tests does not influence the initialization of the instance creators, assuming this is done in the setup phase of the test.
1 parent 17dadf9 commit f765a31

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ MockitoKotlin.registerInstanceCreator<MyClass> { MyClass(5) }
7979
Whenever MockitoKotlin needs to create an instance of `MyClass`, this function is called,
8080
giving you ultimate control over how these instances are created.
8181

82+
These instance creators work on a per-file basis: for each of your test files
83+
you will need to register them again.
84+
8285
### Argument Matchers
8386

8487
Using higher-order functions, you can write very clear expectations about expected values.

mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/MockitoKotlin.kt

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class MockitoKotlin {
3535
/**
3636
* Maps KClasses to functions that can create an instance of that KClass.
3737
*/
38-
private val creators: MutableMap<KClass<*>, () -> Any> = HashMap()
38+
private val creators: MutableMap<KClass<*>, MutableList<Pair<String, () -> Any>>> = HashMap()
3939

4040
/**
4141
* Registers a function to be called when an instance of T is necessary.
@@ -45,7 +45,12 @@ class MockitoKotlin {
4545
/**
4646
* Registers a function to be called when an instance of T is necessary.
4747
*/
48-
fun <T : Any> registerInstanceCreator(kClass: KClass<T>, creator: () -> T) = creators.put(kClass, creator)
48+
fun <T : Any> registerInstanceCreator(kClass: KClass<T>, creator: () -> T) {
49+
val element = Error().stackTrace[1]
50+
51+
creators.getOrPut(kClass) { ArrayList<Pair<String, () -> Any>>() }
52+
.add(element.toFileIdentifier() to creator)
53+
}
4954

5055
/**
5156
* Unregisters an instance creator.
@@ -63,7 +68,16 @@ class MockitoKotlin {
6368
fun resetInstanceCreators() = creators.clear()
6469

6570
internal fun <T : Any> instanceCreator(kClass: KClass<T>): (() -> Any)? {
71+
val stacktrace = Error().stackTrace.filterNot {
72+
it.className.contains("com.nhaarman.mockito_kotlin")
73+
}[0]
74+
6675
return creators[kClass]
76+
?.filter { it.first == stacktrace.toFileIdentifier() }
77+
?.firstOrNull()
78+
?.second
6779
}
80+
81+
private fun StackTraceElement.toFileIdentifier() = "$fileName$className"
6882
}
6983
}

0 commit comments

Comments
 (0)