Reputation: 13377
I have set up this action:
[HttpPost]
[ProducesResponseType(typeof(Category), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateAsync(CategoryViewModel category)
{
if (category == null) return BadRequest();
if (!ModelState.IsValid) return BadRequest(ModelState);
if (!category.Fields.Any()) return BadRequest();
var request = Factory.Create(category);
_categoryService.Save(request);
await _categoryService.SaveChangesAsync();
return Ok(category);
}
The response type should be Category with a status code of 201, but when I run my tests I get a status code of 200. This is my test:
[Test]
public async Task CreateCategory()
{
// Assemble
const string categoryId = "cameras";
var services = ControllerContext.GivenServices();
var controller = services.WhenCreateController();
var field = new Field { CategoryId = categoryId, Name = "Title" };
var category = new CategoryViewModel { Id = categoryId, Name = "Cameras", Fields = new List<Field>{ field } };
// Act
var result = await controller.CreateAsync(category);
var okObjectResult = result as OkObjectResult;
// Assert
okObjectResult.Should().NotBeNull();
Assert.AreEqual(StatusCodes.Status201Created, okObjectResult?.StatusCode);
services.MockCategoryService.Verify(m => m.Save(It.IsAny<Category>()), Times.Once);
services.MockCategoryService.Verify(m => m.SaveChangesAsync(), Times.Once);
}
This test fails on this line: Assert.AreEqual(StatusCodes.Status201Created, okObjectResult?.StatusCode);
because it is returning 200 instead.
Does anyone know why?
Upvotes: 0
Views: 649
Reputation: 4629
The ProducesResponseType-Attribute is not what determines what your Action returns, it is used for things like swagger/OpenAPI to create documentation.
You need to change the return value of your Action to return Created(UriOfTheCreatedResource, category)
instead of return Ok(category)
.
Upvotes: 4