- Annotiere Entität mit @Notnull
- Entität Column(unique=true, nullable= false)
- In Service
- Hole ValidationService wie folgt rein
- @Inject validationService<Entität> validatorService;
- bei speicher soll ValidationService.validate aufrufen
- Erstelle Entität Validation Service
- extends von ValidationService<Entität-Name>
- @Override doCustomValidations Methode
- Super.doCustomValidations und bekomme result zurück
- Finde in repository wenn eine Entität vorhanden ist
- Wenn ja füge in result liste neue violation mithilfe ConstraintVoilationFactory
- Integration Test für Entität
- Speichere eine DTO mithilfe von service
- Lösche DTO ID falls gesetzt
- In Try Block Benutze MockMvc um aufruf zu machen
- Catch Exception
- Exception.getcause() gibt die ConstraintVoilationException
- Iteraiere über violations und finde nexte message der soll angegebene Error sein.
@Test
@Transactional
Public void checkUniqueBookNumber()throws Exception
{
//Initializethedatabase
bookService.save(bookDTO);
bookDTO.setId(null);
try
{
restProjectMockMvc.perform(post("/api/books")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(bookDTO)))
.andExpect(status().isInternalServerError());
}
catch(Exception ex)
{
if(ex.getCause()instanceof ConstraintViolationException)
{
ConstraintViolationExceptionexception=(ConstraintViolationException)ex.getCause();
assertThat(exception.getConstraintViolations().size()).isEqualTo(1);
assertThat(exception.getConstraintViolations().iterator().next().getMessage()).isEqualTo(
BookError.ERROR_BOOK_NR_NOT_UNIQUE);
return;
}
}