我在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'对象:
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);
答案 0 :(得分:1)
var theList = viewResult.Model as IEnumerable<Game>;
这就是诀窍。
答案 1 :(得分:0)
由于它是一个IEnumerable,如果你想让它成为一个数组,你可以使用“ToArray”方法。
Game[] theModel = viewResult.ToArray();
但.Count
应该有用吗?
我们可以看到“repo.GetGames()
”