我应该为返回带有ViewModel的View的控制器操作方法确切测试什么

时间:2018-07-17 09:41:15

标签: c# unit-testing asp.net-core-2.0 xunit

我已经写下了我的第一个单元测试,该测试针对使用Moq框架模拟存储库的控制器操作方法。在此测试中,我可以计算从模拟存储库返回的模型的数量,但是不知道我应该执行哪种测试来验证viewmodel或操作结果输出?

public class HomeControllerUnitTests
{
    [Fact]
    public void IndexTest()
    {
        //Arrange
        var restaurantServiceMock = new Mock<IRestaurantDataCL>();
        var mockList = new List<Restaurant>()
        {
            new Restaurant
            {
                Id = 1,
                Name = "Sabatino's",
                Cuisine = CuisineType.French
            },
            new Restaurant
            {
                Id = 2,
                Name = "Sabatino's",
                Cuisine = CuisineType.Italian
            },
            new Restaurant
            {
                Id = 3,
                Name = "Sabatino's",
                Cuisine = CuisineType.German
            },
            new Restaurant
            {
                Id = 4,
                Name = "Sabatino's",
                Cuisine = CuisineType.None
            },
            new Restaurant
            {
                Id = 5,
                Name = "Sabatino's",
                Cuisine = CuisineType.None
            }
        };

        restaurantServiceMock
            .Setup(x => x.GetAll())
            .Returns(mockList);

        var greeterServiceMock = new Mock<IGreeter>();
        var greeterMessage = "Hello From Unit Test !!!!";
        greeterServiceMock
            .Setup(x => x.GetMessageOfTheDay())
            .Returns(greeterMessage);


        var controller = new HomeController(restaurantServiceMock.Object, greeterServiceMock.Object);

        //act
        var result = controller.Index();

        //Assert
        Assert.NotNull(result);
        var okResult = result.Should().BeOfType<ViewResult>().Subject;
        var restaurants = ((HomeIndexViewModel)okResult.Model).Restaurants.Should().BeAssignableTo<IEnumerable<Restaurant>>().Subject;
        restaurants.Count().Should().Be(5);

        var indexViewModel = okResult.Model.Should().BeAssignableTo<HomeIndexViewModel>().Subject;

        Assert.IsAssignableFrom<HomeIndexViewModel>(indexViewModel);

    }
}

1 个答案:

答案 0 :(得分:0)

这取决于控制器动作应该执行的操作,但是例如,您应该验证是否返回了正确的视图,是否返回了正确的视图模型并声明视图模型的预期状态。请参阅文档以获取有关如何对测试控制器进行单元化的更多信息:

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-2.1

请记住,控制器逻辑应该尽量少。您的业​​务逻辑应在模型中实现。