I still learning Junit and I don't know which approach is better
An observation: "car" is being built on a @BeforeEach method
Example all at once:
@Test public void CarRepository_Id_NotNull() {
Car carBankSlip = carRepository.save(car);
assertNotNull(car.getId());
assertNotNull(car.getUserId());
assertNotNull(car.getColor());
}
Example all separated:
@Test public void CarRepository_Id_NotNull() {
Car carBankSlip = carRepository.save(car);
assertNotNull(car.getId());
}
@Test public void CarRepository_UserId_NotNull() {
Car carBankSlip = carRepository.save(car);
assertNotNull(car.getUserId());
}
@Test public void CarRepository_Color_NotNull() {
Car carBankSlip = carRepository.save(car);
assertNotNull(car.getColor());
}
I tried both, and both works, but I don't know each one serves better the purpose of unit tests
That depends a bit on personal taste. In general, I recommend that a unit test should fail for one reason and not multiple. So this means that you should favor verifying a specific behavior for your class under test within one unit test.
Testing getter/setter may not be worth testing unless you're doing some extra logic in there.
Technically, there's no difference except that with the separated approach, you spend more time typing.
If you still need/want to write some tests, I would recommend finding an approach that works for your team and sticking to it to avoid having different testing approaches.
Personally, I would group them and define the test as following: shouldPopulateAttributesWhenRetrievingCarFromDatabase
(if you really want to keep writing such tests).