0

I have a couple of tests failing in my test class when running them all together. When I run them individually, they all work well. So there must be some conflict in the mocked value which I reuse in multiple tests.

Here is example:

@ExtendWith(SpringExtension::class)
@AutoConfigureMockMvc(addFilters = false)
class BerryStorageTest {
    private lateinit var berryStorage: BerryStorage
    private lateinit var dataB: DataB

    @BeforeEach
    fun setup() {
        dataK = mock()
        whenever(dataB.berries).thenReturn(ConcurrentHashMap())
        this.berryStorage = BerryStorage(dataB)
    }

@Test
    fun `when adding additional berry to berries storage, number of berries increased`() {
        // reset(dataB)
        // dataB = mock()
        whenever(dataB.berries).thenReturn(berriesMapMock)
        berryStorage.addBerry(additionalBerryMock)
        val resultBerries = dataB.berries

        assertThat(resultBerries.size).isEqualTo(2)
}

// Some other tests...
}

What am I missing? I can clearly see through debugging that when the test starts there are 2 berries inside the mocked value instead of 1 value as it is initialized in berriesMapMock. So assert fails because as the result there are 3 berries overall, instead of 2. And one of them is coming from another unit test...

I have the @BeforeEach method to reinitialize the mock, but the problem persists for a couple of my tests.

Edster
  • 143
  • 2
  • 13
  • Do you need to do `dataB` mock on setup?. If `dataB.berries` is not called in the `BerryStorage` constructor then there is no need for it. – cutiko Feb 17 '21 at 18:30
  • It is injected into BerryStorage, so yes, I have to create the dataB mock. – Edster Feb 17 '21 at 19:01
  • You have to create a `dataB` mock, but do you have to define the behavior on the setup? If `BerryStorage` doesn't call `dataB.berries` on the `init` methods then there is no need for the `whenever` in the setup method. – cutiko Feb 17 '21 at 19:16
  • Ahh, i see what you mean. This is something i added after the problem appeared. I was hoping that if i map "whether" to empty hashmap in BeforeEach this might fix the problem. But it did not. Anyway, the result is the same with or without that line :( – Edster Feb 17 '21 at 20:22
  • What is `berriesMapMock`? – cutiko Feb 18 '21 at 03:40
  • This is just a mock data to fill into the berries collection. – Edster Feb 18 '21 at 09:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228887/discussion-between-cutiko-and-edster). – cutiko Feb 18 '21 at 11:07

0 Answers0