I am working on a spring boot project, in my test I want to ensure that the licenseUpdate works. Here are the steps
- create a new pen
- retrieve the testLicense
- update the testLicense with the new pen
- retrieve the license for the new pen
- assert that it is the same license with the updated pen
At step 5
assertThat(lic).isPresent();
it fails because the findByPenSerial did not find the license. I have debugged it and see that the objects are updated correctly so I guess that it is not written into the test database thats why the findByPenSerial returns nothing. How can I manually store the changes to the database after step 4?
@ActiveProfiles("test")
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED)
@Transactional
@SpringBootTest
public class FooTest extends BaseTests {
//...
@Test
public void whenUpdateLicenseToNewPen(){
//create a new pen
String penSerial = "foo";
Optional<PenEntity> newPen = penService.saveBySerial(penSerial);
assertThat(newPen).isPresent();
Optional<LicenseEntity> lic = licenseService.findByPenSerial(testPen.getSerial());
LicenseEntity currentLic = lic.get();
//setting license to another pen
currentLic.setPen(newPen.get());
//save the license
licenseService.update(lic.get().getId(), lic.get());
//find the license now under new serial
lic = licenseService.findByPenSerial(penSerial);
assertThat(lic).isPresent();
assertThat(lic.get().getId()).isEqualTo(currentLic.getId());
}
}
@Service
@AllArgsConstructor
public class LicenseServiceImpl
extends Base<LicenseEntity>
implements LicenseService {
//....
@Override
public Optional<LicenseEntity> save(LicenseEntity entity) {
LOG.debug("creating license for pen {0}", entity.getPen().getSerial());
LicenseEntity lic = licenseRepository.save(entity);
return Optional.ofNullable(lic);
}
@Override
public Optional<LicenseEntity> update(Long id, LicenseEntity entity) {
Optional<LicenseEntity> licToUpdate = licenseRepository.findById(id);
if (licToUpdate.isPresent()){
LicenseEntity currentLic = licToUpdate.get();
BaseBeanUtils.copyPropertiesSkipNulls(entity, currentLic);
LicenseEntity updatedLic = licenseRepository.save(currentLic);
return Optional.ofNullable(updatedLic);
}
return Optional.empty();
}
@Override
public Optional<LicenseEntity> findByPenSerial(String penSerial) {
LicenseEntity license = licenseRepository.findByPenSerial(penSerial);
if (license == null){
return Optional.empty();
}
return Optional.of(license);
}
@Repository("LicenseRepository")
public interface LicenseRepository
extends JpaRepository<LicenseEntity, Long>,
JpaSpecificationExecutor<LicenseEntity> {
LicenseEntity findByPenSerial(String serial);
LicenseEntity findByPenPenId(Long penId);
}