0

I am trying to create an Integration Test for my .Net Core Web Api

But I am always getting a 400 Bad Request response. I am sharing details below

Here is my Controller method

public IActionResult UpdateProductById([FromBody]int id, string description) { var result = ProductService.UpdateProductById(id, description); if (result.Exception == null) return Ok(result); else return BadRequest(result.Exception.Message); } 

Here is my test class (which tries to post)

[Fact] public async Task UpdateProductById_Test_WithProduct() { var product = new { id = 1, description = "foo" }; var productObj= JsonConvert.SerializeObject(product); var buffer = System.Text.Encoding.UTF8.GetBytes(productObj); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await _tester.Client.PostAsync("/api/1.0/UpdateProductById", byteContent); result.StatusCode.Should().Be(HttpStatusCode.OK); } 
3
  • Hi, what's in the exception message? Commented Oct 21, 2018 at 21:03
  • You're hiding the real error when you call 'BadRequest'. Commented Oct 21, 2018 at 21:03
  • PoulBak and Stefan problem solved with Nkosi's comment. Thank you so much for your interest Commented Oct 22, 2018 at 14:35

1 Answer 1

4

The test is sending all the content in the body of the request, yet the action is only binding the id. Most likely the description is null and causing an issue with the update.

Create a model to hold the data

public class ProductModel { public int id { get; set; } public string description { get; set; } } 

Refactor action to get the content from the body of the request

[HttpPost] public IActionResult UpdateProductById([FromBody]ProductModel model) { if(ModelState.IsValid) { var result = ProductService.UpdateProductById(model.id, model.description); if (result.Exception == null) return Ok(result); else return BadRequest(result.Exception.Message); } return BadRequest(ModelState); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.