Issue
I have simple class annotated with @Component and injected repositories like
@Component
class TestsDataPreparer(
private val carRepository: CarRepository
) {
fun withCar(builder: Car.() -> Unit = {}): Car {
return carRepository.save(
Car(
name = builder.name!!
)
)
}
}
which is clear..
But i wonder if it would be ok to do something like this, or if it is considered as anti-pattern.
@Component
class TestsDataPreparer(
val carRepository: CarRepository
) {
fun withCar(builder: Car.() -> Unit = {}): Car {
return carRepository.save(
Car(
name = builder.name!!
)
)
}
}
@Test
fun testCar() {
testsDataPreparer.withCar{this.name="Super-cool-car!"}
assertThat(testsDataPreparer.carRepository.findAll()).hasSize(1)
}
So the question is if it is okay to not inject repository in test class itself, but reuse it from TestsDataPreparer class
Solution
Yes, making an originally private field public just for testing can be considered an antipattern. Instead, you can create a CarRepository
instance and then pass it to TestsDataPreparer
when you create it. But for unit testing, you don't actually need that, you can use a mock and verify that the correct method was called (CarRepository.save
).
Answered By - user3738870
Answer Checked By - Katrina (JavaFixing Volunteer)