How to test a header property in .netcore-3.0?

Viewed 684

According to the documentation, the following adds a Location header to the response.

// POST: api/TodoItems
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
{
    _context.TodoItems.Add(todoItem);
    await _context.SaveChangesAsync();

    //return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
    return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
}

In Xunit, how should I write the Assert part of the unit-test in order to test the value of the Location header?

[Fact]
public async Task Posting_A_ValidTodoItem_Creates_LocationHeader()
{

    // Arrange
    //...

    // Act
    var result = await.controller.PostToDoItem(toDoItem)

    // Assert
    //???
}

Testing the status code and response body has been straight forward, but I haven't been able to test the header yet.

1 Answers

You can test something like this,

// Assert
Assert.NotNull(controller.Response.Header["Location"]);
Related