首页 > 解决方案 > 设置时模拟未按预期运行

问题描述

我正在尝试使用GetAll类的 xUnit-Project 中的名称测试方法AuhtorRepository

public class AuthorRepository : IAuthorRepository
{
    private readonly ISqlDb _db;
    public string Connection { get; set; }
    public AuthorRepository(ISqlDb db)
    {
        _db = db;
    }

    public async Task<List<AuthorModel>> GetAll()
    {
        string sql = "SELECT * FROM Author";
        List<AuthorModel> authors = await _db.LoadDataAsync<AuthorModel, dynamic>(sql, new { }, Connection);
        return authors; 
    }

}

在这个方法中是LoadDataAsync我将在我的测试中模拟的方法。

接口的结构如下所示。

public interface ISqlDb
{
    Task<List<T>> LoadDataAsync<T, U>(string sql, U parameters, string connection);
}

最后执行测试我的xUnit-Project。

using Autofac.Extras.Moq;
using DataAccess.Library;
using Moq;
using Repository.Library.Models;
using Repository.Library.Repositories;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;

namespace RespositoryTests
{
    public partial class AuhtorRepositoryTests
    {
        [Fact]
        public async Task GetAll_ShouldWorkd()
        {
            using (var autoMock = AutoMock.GetLoose())
            {
                //Arrange
                autoMock.Mock<ISqlDb>()
                    .Setup(x => x.LoadDataAsync<AuthorModel, dynamic>("SELECT * FROM Author", new { }, " "))
                    .ReturnsAsync(GetSamples());

                //Act
                var cls = autoMock.Create<AuthorRepository>();
                cls.Connection = " ";
                var expected = GetSamples();

                var acutal = await cls.GetAll();

                //Assert                
                Assert.Equal(expected.Count, acutal.Count);

            }

        }

        private List<AuthorModel> GetSamples()
        {
            var authors = new List<AuthorModel>();
            authors.Add(new AuthorModel { Id = 1, FirstName = "first name", LastName = "lastname" });
            authors.Add(new AuthorModel { Id = 3, FirstName = "Angela", LastName = "Merkel" });
            return authors;
        }
    }
}

项目结构如下: [1]: https://i.stack.imgur.com/F4TPT.png

测试失败并出现以下语句:

消息:System.NullReferenceException:对象引用未设置为对象的实例。

所以我希望测试应该通过。

到目前为止我尝试过的内容:

-> 我用相同的代码写了一个类似的项目,唯一的区别是项目结构。每个接口和类都在同一个测试项目中,并且测试通过了。

而在我的BookApp解决方案中,ISqlDb它适用于DataAccess.Library项目。

所以看起来在模拟中 ReturnAsync 方法没有从我的 GetSamples 返回值。

请记住,

试过了:

 //Act
//var cls = autoMock.Create<AuthorRepository>();
//cls.Connection = "";
var cls = new AuthorRepository(autoMock.Create<ISqlDb>());
cls.Connection = "";
var expected = GetSamples();

var acutal = await cls.GetAll();

//Assert                
Assert.Equal(expected.Count, acutal.Count);

标签: c#moqautofacxunit

解决方案


默认情况下,模拟返回 null,因为模拟成员的调用与设置的不匹配。参考起订量快速入门,以更好地了解如何使用起订量。

您需要在此处使用参数匹配器,因为new { }设置中使用的匿名不会匹配执行测试时实际使用的引用

//...

autoMock.Mock<ISqlDb>()
    .Setup(x => x.LoadDataAsync<AuthorModel, dynamic>("SELECT * FROM Author", It.IsAny<object>(), It.IsAny<string>()))
    .ReturnsAsync(GetSamples());

//...

请注意使用It.IsAny<object>()来允许您传入的任何内容。

通过上述更改,测试按预期通过。


推荐阅读