【问题标题】:xUnit, Moq - test .Net Core RepositoryxUnit,Moq - 测试 .Net Core 存储库
【发布时间】:2019-08-10 08:47:06
【问题描述】:

我正在学习用 xUnit 和 Moq 编写单元测试,我有点问题。我在一个中编写了 2 个测试,我添加了一个类别并全部下载,通过 Assert 或任何它们进行检查。在第二种情况下,我也添加了类别,并且我得到了添加类别的详细信息,不幸的是我无法显示下载类别的详细信息,这是TestCategoryDe​​tails测试。我做错了什么?

using Moq;
using relationship.Models;
using Xunit;
using Xunit.Abstractions;

namespace Testy
{
    public class UnitTest1
    {
        private readonly ITestOutputHelper _output;
        public UnitTest1(ITestOutputHelper output)
        {
            _output = output;
        }

        [Fact]
        public void TestCategoryList()
        {
            var categoryMock = new Mock<ICategoryRepository>();
            var contextMock = new Mock<AppDbContext>();
            categoryMock.Setup(x => x.AddCategory(new GameCategory { Id= 1, Name = "Tester" }));

            var result = categoryMock.Object;
            Assert.NotNull(result.GameCategory());
        }

        [Fact]
        public void TestCategoryDetails()
        {
            var categoryMock = new Mock<ICategoryRepository>();
            var contextMock = new Mock<AppDbContext>();
            categoryMock.Setup(x => x.AddCategory(new GameCategory { Id = 1, Name = "Tester" }));

            var result = categoryMock.Object;
            var categoryDetails = result.GetDetails(1);
            Assert.NotNull(categoryDetails);
        }
    }
}

总的来说,我想通过检查如何添加、编辑、删除、下载所选类别的所有类别和详细信息来测试我的存储库,不幸的是我什么也没做。

【问题讨论】:

    标签: c# asp.net-core .net-core tdd moq


    【解决方案1】:

    你在做什么是你试图测试存储库抽象的模型。但是你想测试你的实现。

    使用 db 上下文进行测试的最佳方法是在内存提供程序中使用真实上下文。详情见: https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/

    最后它可能看起来像这样(第二次测试):

    ...
    
    [Fact]
    public void TestCategoryDetails()
    {
        // arrange
        var categoryRepository = new CategoryRepository(GetContextWithInMemoryProvider());
    
        // act
        categoryRepository.AddCategory(new GameCategory { Id = 1, Name = "Tester" });
        var categoryDetails = categoryRepository.GetDetails(1);
    
        // assert
        Assert.NotNull(categoryDetails);
    }
    
    private AppDbContext GetContextWithInMemoryProvider()
    {
        // create and configure context
        // see: https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/
    }
    
    ...
    

    【讨论】:

    • 可以说这不再是单元测试了吗?由于测试将调用数据库(即使它是内存数据库)?这是 IMO 的集成测试。
    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2018-05-27
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多