Xunit - 带有最小起订量的测试用例,用于 C# 中可能的存储库测试用例?

Xunit - Test Case With Moq for Below Repository Test cases Possible in C#?

我正在使用 Moq 框架做测试用例。 对于下面的存储库测试用例,我在设置正确后收到空值 Setup.I 不应该知道这种类型的回购代码模拟是可能的或者 not.Any 帮助表示赞赏。 .

public class DocumentRepository : IDocumentRepository
{
    private IDataSourceFactory director;
    private IDataSourceRepository dataSourceRepository;
    private IDocumentResourceRepository documentSourceRepository;
    private IConfiguration configuration;
    private ICryptography<string> cryptography;
    private readonly IMapper mapper;

    public DocumentRepository(IDataSourceFactory _director, IConfiguration _configuration, ICryptography<string> _cryptography, IMapper _mapper)
    {
        director = _director;
        dataSourceRepository = _director.GetDataSourceRepository(Enums.DataSourceType.SQL)();
        documentSourceRepository = _director.GetDocumentResourceRepository(Enums.DataSourceType.SQL)();
        configuration = _configuration;
        cryptography = _cryptography;
        mapper = _mapper;
    }

    /// <inheritdoc/>
    public async Task<(byte[]?, string)> GetFileContentAsync(string resource_id)
    {
        //get file by resource_id
        
        var documentLinkStr = cryptography.Decrypt(HttpUtility.UrlDecode(resource_id)?.Trim()?.Replace(" ","+"));
        var documentLink = JsonConvert.DeserializeObject<DocumentLink>(documentLinkStr);

        if (documentLink is null)
            throw new Exception("Invalid Resource Id");

        documentSourceRepository = director.GetDocumentResourceRepository((Enums.DataSourceType)Enum.Parse(typeof(Enums.DataSourceType), 
                                                                            documentLink.DocumentSource))();
        return await documentSourceRepository.GetDocument(documentLink);
    }
    }

下面是我的测试用例Class:

    public class DocumentRepositoryTests
{
    private readonly Mock<IDataSourceFactory> _dataSourceFactoryMock;
    private readonly Mock<IDataSourceRepository> _dataSourceRepositoryMock;
    private readonly Mock<IDocumentResourceRepository> _documentSourceRepositoryMock;
    private readonly Mock<IConfiguration> _configurationMock;
    private readonly Mock<ICryptography<string>> _cryptographyMock;
    private readonly Mock<IMapper> _mapperMock;
    private IDocumentRepository? documentRepository;
    //string[] demoData;

    public DocumentRepositoryTests()
    {
        _dataSourceFactoryMock = new Mock<IDataSourceFactory>(MockBehavior.Strict);
        _dataSourceRepositoryMock = new Mock<IDataSourceRepository>();
        _documentSourceRepositoryMock = new Mock<IDocumentResourceRepository>();
        _configurationMock = new Mock<IConfiguration>();
        _cryptographyMock = new Mock<ICryptography<string>>();
        _mapperMock = new Mock<IMapper>();
    }

   [Fact]
    public void If_validResourceIdValue_Pass_GetDocumentAsync_Return_FilesByteArraysAndFileName()
    {
        //Arrange
        string validResourceIdValue = "1234567";
        DocumentLink documentLink = new DocumentLink("1B2F00DD-3A2D-4F17-A9EF-50709ABD9932", "SQL", "DocumentId1");
        string documentLinkString = JsonConvert.SerializeObject(documentLink);

        string fileName = "Demo.pdf";
        string demoData =
           @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 
            tempor incididunt ut labore et dolore magna aliqua. Porta non pulvinar
            neque laoreet suspendisse. Turpis in eu mi bibendum. Aliquam ut
            porttitor leo a diam sollicitudin. Faucibus interdum posuere lorem ipsum
            dolor sit. Congue eu consequat ac felis donec et odio. Bibendum arcu
            vitae elementum curabitur vitae nunc sed velit. Convallis tellus id
            interdum velit laoreet. Sollicitudin tempor id eu nisl nunc mi ipsum
            faucibus vitae. Justo donec enim diam vulputate ut pharetra sit. Proin
            sed libero enim sed faucibus. Ornare quam viverra orci sagittis eu. Odio
            ut enim blandit volutpat maecenas volutpat blandit. Erat velit
            scelerisque in dictum non consectetur a.
            Morbi enim nunc faucibus a. Varius morbi enim nunc faucibus a
            pellentesque sit. Urna duis convallis convallis tellus id interdum velit.
            Dictumst quisque sagittis purus sit. Praesent tristique magna sit amet
            purus gravida. Aliquam eleifend mi in nulla. Fringilla phasellus faucibus
            scelerisque eleifend donec pretium vulputate. Mi bibendum neque
            egestas congue quisque egestas. Facilisis leo vel fringilla est ullamcorper.
            Ornare lectus sit amet est placerat in egestas erat imperdiet. Orci a
            scelerisque purus semper eget. Tortor posuere ac ut consequat semper
            viverra nam libero. Parturient montes nascetur ridiculus mus.";

        byte[] demoBytes = Encoding.UTF8.GetBytes(demoData);


        var dataSourceRepositoryMock = Mock.Of<Func<IDataSourceRepository>>();
        _dataSourceFactoryMock.Setup(p => p.GetDataSourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>())).Returns(dataSourceRepositoryMock);

        //var documentResourceRepository = Mock.Of<Func<IDocumentResourceRepository>>(MockBehavior.Strict);
        var documentResourceRepository = Mock.Of<Func<IDocumentResourceRepository>>();
        _dataSourceFactoryMock.Setup(p => p.GetDocumentResourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>())).Returns(documentResourceRepository);


        //Mock.Get(documentResourceRepository).Setup(s => s.Invoke()).Returns(documentResourceRepository);

        //_dataSourceFactoryMock.SetupSequence(p => p.GetDocumentResourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>()))
        //            .Returns(documentResourceRepository)
        //            .Returns(documentResourceRepository);

        _cryptographyMock.Setup(p => p.Decrypt(It.IsAny<string>())).Returns(documentLinkString);

        _documentSourceRepositoryMock.Setup(p => p.GetDocument(documentLink)).ReturnsAsync((demoBytes, fileName));

        documentRepository = new DocumentRepository(_dataSourceFactoryMock.Object, _configurationMock.Object, _cryptographyMock.Object, _mapperMock.Object);

        //Act
        var response = documentRepository.GetFileContentAsync(validResourceIdValue).Result;

        //Assert
        Assert.True(response.Item1 == demoBytes);
        Assert.True(response.Item2 == fileName);
    }

但是这一行总是 return 在正确的 Mock 设置之后为 null 然后还有:

     documentSourceRepository = director.GetDocumentResourceRepository((Enums.DataSourceType)Enum.Parse(typeof(Enums.DataSourceType), 
                                                                            documentLink.DocumentSource))();

这个方法可以用最小起订量测试用例吗?

首先设置 IDocumentResourceRepository 模拟

var repoMock = Mock.Of<IDocumentResourceRepository>();
repoMock
  .Setup(r => r.GetDocument(It.IsAny<DocumentLink>())
  ...

然后设置 GetDocumentResourceRepository 方法的 mock

  • 它 returns 一个 returns IDocumentResourceRepository mock
  • 的函数
dataSourceFactoryMock
   .Setup(p => p.GetDocumentResourceRepository(It.IsAny<DataSourceType>()))
   .Returns(() => repoMock.Object);

更新#1

这是上述代码的 fine-tuned 版本(@Dipak Rathod 所做的更改)

_documentSourceRepositoryMock
   .Setup(p => p.GetDocument(It.IsAny<DocumentLink>()))
   .ReturnsAsync(()=>(demoBytes, fileName)); 

_dataSourceFactoryMock 
   .Setup(p => p.GetDocumentResourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>())) 
   .Returns(() => _documentSourceRepositoryMock.Object);