ASP.NET WebApi unit testing with Request.CreateResponse

后端 未结 5 1989
遇见更好的自我
遇见更好的自我 2020-12-04 06:42

I am trying to write some unit tests for my ApiController and faced some issues. There is a nice extension method called Request.CreateResponse that helps a lot with generat

5条回答
  •  萌比男神i
    2020-12-04 07:18

    For Web API 2, you can simply add

    controller.Request = new HttpRequestMessage();
    controller.Configuration = new HttpConfiguration();
    

    Like so

    [TestMethod]
    public void GetReturnsProduct()
    {
        // Arrange
        var controller = new ProductsController(repository);
        controller.Request = new HttpRequestMessage();
        controller.Configuration = new HttpConfiguration();
    
        // Act
        var response = controller.Get(10);
    
        // Assert
        Product product;
        Assert.IsTrue(response.TryGetContentValue(out product));
        Assert.AreEqual(10, product.Id);
    }
    

    It's important to set Request and Configuration on the controller. Otherwise, the test will fail with an ArgumentNullException or InvalidOperationException.

    See here for more info.

提交回复
热议问题