0

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?

1
  • 1
    Why do you think it should be 201? You're calling the Ok() method (as in OK 200). Commented Jul 25, 2019 at 15:25

1 Answer 1

4

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).

Documentation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.