在moq单元测试中如何修复"对象引用未设置为对象的实例"

时间:2018-04-25 17:56:26

标签: unit-testing model-view-controller boolean nunit moq

好的我正在尝试创建一个测试,检查我的徽章方法是否真的为PlayersBadge添加了徽章。它有效,但我不知道如何正确测试。主要问题是我对moq的理解。

这是我在PlayerID,BadgeID和GameID中采用的方法。

 public bool Badge(int pID, int bID, int gID = 0)
    {
        var list = EliminationDbContext.PlayerBadges.Where(x => x.Badge.BadgeID.Equals(bID) && x.Player.PlayerID.Equals(pID));
        if (list.Any() != true)
        {
            PlayerBadge b = new PlayerBadge { PlayerID = pID, BadgeID = bID, DateEarned = DateTime.Today, GameID = gID };
            _RepoManager.PlayerBadges.Add(b);
            _RepoManager.SaveDb();
            return true;
        }
        return false;
    }

目前我收到此错误"对象引用未设置为对象的实例"我认为这是因为我没有正确设置PlayerBadge的模拟,但我不确定如何解决这个问题

        [Test]
        public void testing()
        {    //Arrange
            var mock = new Mock<IRepoManager>();
            var mockRequest = new Mock<PlayerBadge>();

            var dManager = new TestMoq(mock.Object);
            //set mockRequest to playerBadge
            mockRequest.Setup(x => x.Badge.PlayerBadges.Add(badge));

            //Act
            //Object reference not set to an instance of an object on this line 
            dManager._RepoManager.PlayerBadges.Add(mockRequest.Object);
            dManager._RepoManager.Badges.Badge(1, 2, 0);

            Assert.That(dManager._RepoManager.PlayerBadges.GetPlayerBadges().Count() >= 1);
}

0 个答案:

没有答案