为数据创建编写单元测试时遇到问题 - jhipster
Trouble with writing units tests for data creation - jhipster
我在我的实体资源 class 中修改了创建方法,如下所示:
@Timed
public ResponseEntity<Void> create(@Valid @RequestBody Distance distance) throws URISyntaxException {
log.debug("REST request to save Distance : {}", distance);
if (distance.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new distance cannot already have an ID").build();
}
if(!SecurityUtils.isUserInRole(AuthoritiesConstants.ADMIN))
{
//set the current logged in user as the user if they are not admin
distance.setUser(userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).get());
}
distanceRepository.save(distance);
return ResponseEntity.created(new URI("/api/distances/" + distance.getId())).build();
}
我已经做到了,如果当前登录的用户不是管理员,则将用户设置为当前登录的用户。
这在我构建和 运行 时效果很好。但是我在为它编写单元测试时遇到了麻烦。
这是测试数据创建的当前代码:
@Test
@Transactional
public void createDistance() throws Exception
{
int databaseSizeBeforeCreate = distanceRepository.findAll().size();
System.out.println("Size: "+databaseSizeBeforeCreate);
// create security-aware mockMvc
restDistanceMockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
System.out.println("Distance: "+distance.toString());
// Create the Distance
restDistanceMockMvc.perform(post("/api/distances")
.with(user("user"))
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(distance)))
.andExpect(status().isCreated());
// Validate the Distance in the database
List<Distance> distances = distanceRepository.findAll();
assertThat(distances).hasSize(databaseSizeBeforeCreate + 1);
Distance testDistance = distances.get(distances.size() - 1);
assertThat(testDistance.getDateTime().toDateTime(DateTimeZone.UTC)).isEqualTo(DEFAULT_DATE_TIME);
assertThat(testDistance.getDistance()).isEqualTo(DEFAULT_DISTANCE);
}
此测试失败并显示错误消息:
java.lang.AssertionError: Status expected:<201> but was:<403>
我的问题是:为什么我在尝试创建新条目时收到 403 状态?以及如何正确创建新条目。
如果我没有发布足够的信息,请告诉我。
注意:我正在学习本书中的教程:http://www.infoq.com/minibooks/jhipster-mini-book
我成功了。执行 POST 时,您需要发送 CSRF (.with(csrf())):
restDistanceMockMvc.perform(post("/api/distances")
.with(csrf())
.with(user("user"))
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(distance)))
.andExpect(status().isCreated());
我在我的实体资源 class 中修改了创建方法,如下所示:
@Timed
public ResponseEntity<Void> create(@Valid @RequestBody Distance distance) throws URISyntaxException {
log.debug("REST request to save Distance : {}", distance);
if (distance.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new distance cannot already have an ID").build();
}
if(!SecurityUtils.isUserInRole(AuthoritiesConstants.ADMIN))
{
//set the current logged in user as the user if they are not admin
distance.setUser(userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).get());
}
distanceRepository.save(distance);
return ResponseEntity.created(new URI("/api/distances/" + distance.getId())).build();
}
我已经做到了,如果当前登录的用户不是管理员,则将用户设置为当前登录的用户。
这在我构建和 运行 时效果很好。但是我在为它编写单元测试时遇到了麻烦。
这是测试数据创建的当前代码:
@Test
@Transactional
public void createDistance() throws Exception
{
int databaseSizeBeforeCreate = distanceRepository.findAll().size();
System.out.println("Size: "+databaseSizeBeforeCreate);
// create security-aware mockMvc
restDistanceMockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
System.out.println("Distance: "+distance.toString());
// Create the Distance
restDistanceMockMvc.perform(post("/api/distances")
.with(user("user"))
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(distance)))
.andExpect(status().isCreated());
// Validate the Distance in the database
List<Distance> distances = distanceRepository.findAll();
assertThat(distances).hasSize(databaseSizeBeforeCreate + 1);
Distance testDistance = distances.get(distances.size() - 1);
assertThat(testDistance.getDateTime().toDateTime(DateTimeZone.UTC)).isEqualTo(DEFAULT_DATE_TIME);
assertThat(testDistance.getDistance()).isEqualTo(DEFAULT_DISTANCE);
}
此测试失败并显示错误消息:
java.lang.AssertionError: Status expected:<201> but was:<403>
我的问题是:为什么我在尝试创建新条目时收到 403 状态?以及如何正确创建新条目。
如果我没有发布足够的信息,请告诉我。
注意:我正在学习本书中的教程:http://www.infoq.com/minibooks/jhipster-mini-book
我成功了。执行 POST 时,您需要发送 CSRF (.with(csrf())):
restDistanceMockMvc.perform(post("/api/distances")
.with(csrf())
.with(user("user"))
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(distance)))
.andExpect(status().isCreated());