简体   繁体   中英

xUnit, Moq - test .Net Core Repository

I'm learning to write unit tests in xUnit and Moq, I have a problem somewhat. I wrote 2 tests in one, I add a category and download all, checking through Assert or whatever they are. In the second case, I also add categories, and I get the details of the added category, unfortunately I can not display the details of the downloaded category, it's the TestCategoryDetails test. What am I doing wrong?

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);
        }
    }
}

In general, I wanted to test my repository by checking how add, edit, delete, download all categories and details of the selected one, unfortunately I'm not doing anything.

What are you doing is you are trying to test the mockup of the repository abstraction. But you want to test your implementation.

What works well to test with db context is to use in memory provider for the real context. For the details see: https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/

At the end it may look like this (second test):

...

[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/
}

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM