如何对插入数据库并保存的void函数进行单元测试?

时间:2018-04-23 14:40:01

标签: unit-testing testing interface moq void

我在我的界面中有这个功能,它在db中创建一个新的PlayersBadge条目。我必须编写单元测试,并且我已经卡住了。

public void 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 player doesn't have Badge create new Badge
            if (list.Any() != true)
            {
                PlayerBadge b = new PlayerBadge { PlayerID = pID, BadgeID = bID, DateEarned = DateTime.Today, GameID = gID };
                EliminationDbContext.PlayerBadges.Add(b);

            EliminationDbContext.SaveChanges();
        }
    }

1 个答案:

答案 0 :(得分:0)

您有几种选择。其中之一是将db通信职责交给Repository类,并在业务类中注入这些实现。编写单元测试时,您可以模拟存储库并验证它们。

另一种选择是直接模拟DataContext,如下所示:

    private Mock<DataContext> _mockedContext;
    private Mock<DbSet<MyEntity>> _mockedMyEntitiyDbSet;

在你的测试用例中:

    [Test]
    public void CargoTicket_WithValidRequest_Verify_SaveChanges()
    {
        //assuming DbContext injected to your _sut object in setup
        MockDbSet(myEntities);
        _sutObject.Badge(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()); // SaveChanges calling in here
        _mockedContext.Verify(s => s.SaveChanges(), Times.Once);
    }

您可以按如下方式模拟DbSet:

    private void MockDbSet(List<MyEntity> myEntities)
    {
        _mockedMyEntitiyDbSet= new Mock<DbSet<MyEntity>>().SetupData(myEntities);
        _mockedContext.Setup(s => s.MyEntities).Returns(_mockedMyEntitiyDbSet.Object);
    }