I have the following test that generates an invitation with a company id and an email. Then, we generate a second with the same company id and email. This should violate the unique constraint on the DB (See the Invitation entity). Thing is, the test passes as listed below (the transaction is never committed for the second insert, I guess)
If I do a findAll() after the second insert (see the comment below) I get an exception on the line where the findAll() is that the index violation has occurred.
How do I make the methods in the UserService commit their transactions when the method returns, so the test code will throw an exception as-is?
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserServiceTest {
... Everything is autowired
@Test
public void testCreateInvitation() {
String email = "test2@example.com";
Company company = userService.createCompany("ACMETEST", tu);
assertTrue(invitationRepository.count() == 0l);
assertNotNull(userService.sendInvitation(company, email));
assertTrue(invitationRepository.count() == 1l);
assertTrue(invitationRepository.findAllByEmail(email).size() == 1);
// Second should throw exception
userService.sendInvitation(company, email);
// If this line is uncommented, I get key violation exception, otherwise, test passes!!!!????
//Iterable<Invitation> all = invitationRepository.findAll();
}
Invitation class and constraint:
@Entity
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"email", "company_id"}))
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
@Data
public class Invitation {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
String id;
@ManyToOne
@JoinColumn(name="company_id")
private Company company;
String email;
Date inviteDate;
Date registerDate;
}
User Service:
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class UserService {
public Invitation sendInvitation(Company company, String toEmail) {
Invitation invitation = new Invitation();
invitation.setCompany(company);
invitation.setInviteDate(new Date());
invitation.setEmail(toEmail);
try {
// TODO send email
return invitationRepository.save(invitation);
} catch (Exception e) {
LOGGER.error("Cannot send invitation: {}", e.getMessage());
}
return null;
}
}