Ed Holloway-George
03/26/2025, 12:02 PM```class FakeRepo: Repo {
private val users = mutableSetOf<String>()
fun addUser(name: String) {
users.add(name)
}
fun getUserCount(): Int {
return users.size
}
}
class SomeService(val repo: Repo) {
fun addUser(name: String) {
userRepository.addUser(name)
}
fun getUserCount(): Int {
return userRepository.getUserCount()
}
}```
If you write tests in this form:
```class SomeServiceTest {
private val repo = FakeRepo()
private val sut = SomeService(repo)
@Test
fun test1() {
service.registerUser("Alice")
val result = sut.getUserCount()
assertEquals(1, result)
}
@Test
fun test2() {
service.registerUser("Bob")
service.registerUser("Charlie")
val result = sut.getUserCount()
assertEquals(2, result)
}
}```
Each individual test will pass if it executes first, but wont pass if it's executed after the other. As the order tests are run isn't guaranteed, this is a common cause of issues with fakes that hold state.Am I right here? The correct approach would be to init
sut
in a @BeforeTest
method right? One of my colleagues mentioned FakeRepo
would be recreated every time without @BeforeTest
dave08
03/26/2025, 12:25 PMdave08
03/26/2025, 12:28 PMdave08
03/26/2025, 12:31 PMEd Holloway-George
03/26/2025, 12:31 PMrepo
and sut
are generated every time so I guess this is likely only a problem when Singleton object
are used. That seems to go against everything I thought I knew about kotlin testsEd Holloway-George
03/26/2025, 12:32 PMdave08
03/26/2025, 12:38 PMdave08
03/26/2025, 12:39 PM