vendredi 1 janvier 2016

Trouble with writing units tests for data creation - jhipster

I have modifier the create method in my entity resource class as follows:

@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();
}

I have made it so that if the currently logged in user is not an Admin, set the user to to the currently logged in user.

This works well when I build and run it. But I am having trouble writhing unit tests for it.

Here is the current code for testing data creation:

@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);
}

This test fails with the error message :

java.lang.AssertionError: Status expected:<201> but was:<403>

My question is: Why am I getting a 403 status when trying to create a new entry ? and how do I correctly create a new entry.

Pls let me know if I have not posted enough info.

Note: I am following the tutorial from this book: http://ift.tt/1N9uq8v

Aucun commentaire:

Enregistrer un commentaire