我正在VS2012中使用NSubstitute运行测试,并且试图将模型转换为列表或可以计数的东西。这是代码:

    [TestMethod]
    public void StartedGame()
    {
        // arrange
        var repo = Substitute.For<IGameRepository>();
        IEnumerable<Game> expectedGames = new List<Game>
            {
                new Game{ gameTypeID = 1, hasStarted = false, ID = 1, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 1, hasStarted = false, ID = 2, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 2, hasStarted = false, ID = 3, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 2, hasStarted = false, ID = 4, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 1, hasStarted = false, ID = 5, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false}
            };
        repo.GetGames().Returns(expectedGames);
        var sut = new GameController(repo);

        // act
        var actual = sut.GameMenuStart();
        // assert
        //Assert.IsInstanceOfType(actual, typeof(ViewResult));
        var viewResult = actual as ViewResult;

        Assert.IsNotNull(viewResult);
    }


调试时,我可以将鼠标悬停在“ viewResult”上并查看“模型”,然后在其中看到条目和“计数”,但是如何实现?我尝试过像这样将对象投射到“游戏”对象:

Game[] theModel = (Game[])viewResult.Model;


并列出更多内容,但始终失败。
有任何想法吗?

编辑:viewResult的类型:System.Web.Mvc.ViewResult

这是此函数内的其余代码:

        var repo = Substitute.For<IGameRepository>();
        IEnumerable<Game> expectedGames = new List<Game>
            {
                new Game{ gameTypeID = 1, hasStarted = false, ID = 1, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 1, hasStarted = false, ID = 2, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 2, hasStarted = false, ID = 3, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 2, hasStarted = false, ID = 4, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false},
                new Game{ gameTypeID = 1, hasStarted = false, ID = 5, isOver = false, isPublic = true, maxPlayers = 2, someoneReported = false}
            };
        repo.GetGames().Returns(expectedGames);
        var sut = new GameController(repo);

最佳答案

var theList = viewResult.Model as IEnumerable<Game>;

这成功了。

关于c# - 将模型转换为MVC测试中的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16549351/

10-09 19:05