Is it possible to "Reset" an object in a test?
# announcements
l
Is it possible to "Reset" an object in a test?
a
Have a look at mockk.io
g
You won't believe me but it's called
reset()
in Mockito 🙂. It's also a sign of a poor test.
l
I meant resetting a kotlin object declaration
I'm not sure if it's a sign of a poor test. My object keeps a map that should be a single instance during the whole JVM
But one test will dirty another test due to this map, as I'm not able to reset the JVM in-execution
So I wanted to reinitialize this singleton only for tests, but in a real environment this will never happen
g
My object keeps a map that should be a single instance during the whole JVM
I agree with @ghedeon, it looks as some bad design and hack for test
j
@LeoColman I would recommend using a DI framework to own this map. The map instance could be created as part of creating some overall application object. The framework can then inject the shared instance into the constructors of any objects that require access to it. Then for tests that require a fully wired-up application you can create a brand new application instance, and for unit tests you can provide a map instance for the object you are testing. Plenty of benefits in moving towards that kind of model. Statically accessible mutable state is a common pain point and worth avoiding where you can.
💯 1
It's totally possible to do something like
Copy code
@BeforeEach
fun beforeEach() {
  myStaticMap.clear()
}
but it's pretty hacky and I think it'll burn you sooner or later.
âž• 1
m
@ghedeon agree that using reset on Mockito/mockk is often a smell, but if you're using junit5 and life cycle of instance, it now becomes mandatory. A blog post about doing that to improve performance of you're tests. As it's faster to reset a mock than to create a new one. Pros and cons to this approach, like all decisions we make.
l
I'm creating a library, and basically the whole point of it is to have this static map
It's a very small library, which only point is to hold onto key-value and act upon these
It has 2 classes. Wiring up a DI framework, factory out the class creation and such seems a bit overkill for this very simple thing
I thought that maybe I could delete the instance via reflection or something, just for the test that uses the class that keeps the map
m
I think your best route may be a
internal fun clear()
defined in your structure that clears it out. Won’t be visible outside the module, but will be available to tests. I don’t think there’s a way to ‘clear memory structure’ from code otherwise.
j
For consumers of your library, will their tests then hit the same problem though?
l
That's right, @Jonathan Mew! I didn't think of that possibility
978 Views