我有一个TestUtil类,它可以帮助我在完全集成测试期间插入一些数据。它有以下方法:
@Autowired private AccountRepository accountRepo;
@Autowired private EntityManager entityManager;
@Transactional
public URI createAccountAndReturnAccountURI(TestRestTemplate restTemplate, String userName, String password) {
HttpHeaders headers = getApplicationJsonHeaders();
String emailAddress = userName + "@bla.com";
String accountRequestBody =
"{\"username\": \"" + userName + "\", \"password\": \"" + password + "\", \"emailAddress\": \""
+ emailAddress + "\", \"roles\": [\"" + Constants.ROLE_USER + "\"]}";
HttpEntity<String> accountEntity = new HttpEntity<>(accountRequestBody, headers);
URI accountLocation = restTemplate.postForLocation(Constants.ACCOUNTSPATH, accountEntity);
if (accountLocation == null)
throw new RuntimeException("Failed to setup test, accountLocation was null.");
//Technically this is not a full integration test because then we'd have to receive emails,
//extract the activation token and make a call to activate the acoount
Account account = accountRepo.findByUsername(userName);
account.setEnabled(true);
entityManager.persist(account);
entityManager.flush();
return accountLocation;
}
正如您可能从代码中的评论中了解到的那样,通常帐户的enabled
设置为false
,直到用户使用其电子邮件地址中的令牌验证其帐户为止。在继续测试之前从电子邮件中提取此令牌并使用它激活每个帐户会有点多,所以我尝试手动更改帐户的enabled
属性。但是,这并不会抛出任何异常,但它不会在{TIME}中将enabled
属性更改为true
。如果我在最后一行设置了断点,则enabled
仍然是数据库中的false
。如果我在那一刻终止整个应用程序,enabled
在数据库中变为true
,我想它实际上就结束了事务。但这对我来说太晚了。有没有办法做到这一点?或者我是否被迫通过某种方式监控入站激活电子邮件的测试电子邮件地址?还有另一个中间解决方案来查询令牌表并从那里获取它,但这也非常难看。
顺便说一下,我试图开始并提交事务(entityManager.getTransaction().begin();
),但后来我得到例外java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead