mardi 6 février 2018

Missing responsebody with MockMvc in Spring restAPI

Im trying to make a small test to test my Spring rest API. my controller looks like this:

@RestController
@RequestMapping("/tokenservice/v1")

public class TokenController {

  private ConfigService configService = new ConfigService();

  // PassiveExpiringMap takes millisecond parameter, and will automatically remove any entry that has expired when the map is accessed, before returning anything. Is not Synq
  private PassiveExpiringMap<String, SensitiveData> dataStores = new PassiveExpiringMap<String, SensitiveData>(configService.getTTL());

  // wrapper for dataStores. Collections.synchronizedMap is used to make the map thread-safe
  private Map<String, SensitiveData> synqMap = Collections.synchronizedMap(dataStores);

  // Routing to the post method. Receives text/plain and returns a "random" UUID back.  https://example:8443/tokenservice/v1/sensitivedata
  @RequestMapping(value = "/sensitivedata", method = RequestMethod.POST, consumes = "text/plain")
  public String postMethod(@RequestBody String secretThings) {
    String token = UUID.randomUUID().toString();
    SensitiveData sensitiveData = new SensitiveData(token, secretThings);
    synqMap.put(token, sensitiveData);
    return token;
  }

  // Routing to the get method. Gets data that matches UUID token.     https://example:8443/tokenservice/v1/sensitivedata?token=<UUID>
  @GetMapping("/sensitivedata")
  public String getData(@RequestParam("token") String token) {
    if (synqMap.containsKey(token)) {
      return synqMap.get(token).getDataToStore();
    } else {
      return "Token not found or has expired";
    }
  }
}

My test looks like this:

MvcResult result = mvc.perform(post("/tokenservice/v1/sensitivedata")
      .with(user("user1").password("secret1"))
      .contentType("text/plain;charset=UTF-8")
      .content("testdata4"))
      .andReturn();

    String token = result.getResponse().getContentAsString();

I thought i would be able to get the token from the body but when i run the test the responsebody is emtpy.

Can see that it hits the correct method and it posts the body

But the response is empty instead of returning the "token"

Aucun commentaire:

Enregistrer un commentaire