【问题标题】:NSubstitute with DbConnectionNSubstitute 与 DbConnection
【发布时间】:2020-11-20 22:52:28
【问题描述】:

我需要将 DbConnection 传递给我的班级。 为此,我正在使用 NSubstitute。 但是当我运行测试时,会出现以下错误: “System.NullReferenceException:对象引用未设置为对象的实例。Dapper”

我的测试

public class SceneApplicationServiceTest
{
    private readonly DbConnection _connection = Substitute.For<DbConnection>();
    ISceneApplicationService _sceneApplicationService;

    public SceneApplicationServiceTest()
    {
        _sceneApplicationService = new SceneApplicationService(_connection);
    }

    [Fact]
    public async Task ShouldBePossibleSuccessfullyGetByProgramScript()
    {
        const long programId = 1;
        const string scriptId = "2";            

        await _sceneApplicationService.GetByProgramScript(programId, scriptId);

        await _sceneApplicationService.Received(1).GetByProgramScript(programId, scriptId);
    }
}

我的方法

 public class SceneApplicationService : ISceneApplicationService
{
    private readonly DbConnection _connection;
    
    public SceneApplicationService(DbConnection connection)
    {
        _connection = connection;
    }

    public async Task<IEnumerable<LegacySceneResponse>> GetByProgramScript(long programId, string scriptId)
    {
        object parameters = new 
        {
            CodigoPrograma = programId,
            CodigoRoteiro = scriptId
        };

        if (!ObjectValidation.IsInvalidAnyNullOrEmpty(parameters)) ;

        return await _connection.QueryAsync<LegacySceneResponse>(GetScenesByScriptAndProgram.Query, parameters);
    }}

当测试尝试运行“QueryAsync”时发生错误

有什么想法吗?

【问题讨论】:

  • 嗨豪尔赫!您不能在这里使用_sceneApplicationService.Received(1)...,因为_sceneApplicationService 不是替代品。我建议将NSubstitute.Analyzers 添加到您的测试项目中,这将有助于选择这样的案例。

标签: c# .net-core xunit nsubstitute dbconnection


【解决方案1】:

看这里,它是 dapper 扩展的最小起订量:

https://github.com/UnoSD/Moq.Dapper

QueryAsync 是 Dapper nuget 的扩展方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    相关资源
    最近更新 更多