【问题标题】:Moq DbContext with async test throwing error带有异步测试抛出错误的 Moq DbContext
【发布时间】:2017-09-05 18:09:27
【问题描述】:

这个测试有问题:

    [Test]
    public async Task Add_async_vaild_test_entity_to_database_should_be_added()
    {
        // Setup Moq
        var mockSet = new Mock<DbSet<SingleChoiseTest>>();
        var mockContext = new Mock<NoezaTestContext>();
        mockContext.Setup(m => m.SingleChoiseTests).Returns(mockSet.Object);

        // Perform action
        var operations = new SingleChoiseTestOperations(mockContext.Object);
        await operations.AddSingleChoiseTest(new SingleChoiseTest("question", new Answer("d1", false),
            new Answer("d2", false), new Answer("d3", false), new Answer("d4", true)));

        mockSet.Verify(t => t.Add(It.IsAny<SingleChoiseTest>()), Times.Once);
        mockContext.Verify(m => m.SaveChangesAsync(), Times.Once);
    }

我正在测试这个功能:

    public async Task AddSingleChoiseTest(SingleChoiseTest singleChoiseTest)
    {
        if (singleChoiseTest == null)
            throw new NullReferenceException("Test cannot be null.");

        if (!singleChoiseTest.IsValid())
        {
            throw new ArgumentException("Test is not vaild.");
        }

        using (_context)
        {
            _context.SingleChoiseTests.Add(singleChoiseTest);
            await _context.SaveChangesAsync();
        }
    }

当我运行测试时,它会抛出以下异常: System.NotSupportedException : 非虚拟(在 VB 中可覆盖)成员上的设置无效:m => m.SingleChoiseTests

【问题讨论】:

    标签: c# entity-framework nunit moq


    【解决方案1】:

    正如错误试图告诉你的那样,你只能为virtual 成员调用Setup()

    您需要将SingleChoiseTests 设为虚拟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2020-11-24
      • 2019-09-05
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      相关资源
      最近更新 更多