我在我的实体资源类中修改了create方法,如下所示:
@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:预期状态:&lt; 201&gt;但是:&lt; 403&gt;
我的问题是:为什么我在尝试创建新条目时会获得403状态?以及如何正确创建新条目。
如果我没有发布足够的信息,请告诉我。
注意:我正在遵循本书中的教程:http://www.infoq.com/minibooks/jhipster-mini-book
答案 0 :(得分:1)
我做到了。在进行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());