NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException:无法为 IDbCommand 返回类型为 Task`1 的值。 (预期类型为Void)

问题描述 投票:0回答:1

我有以下界面,在应用程序中我使用 Dapper,我尝试使用 NSubstitude 模拟查询和连接。

public interface IDapperContextBuilder
{
    IDbConnection  CreateConnection();
}

在单元测试中

[Fact]
        public void GetAllAuthority()
        {
            // Arrange
            var connectionFactory = Substitute.For<IDapperContextBuilder>();
            var fakeConnection = Substitute.For<IDbConnection>();
            connectionFactory.CreateConnection().Returns(fakeConnection);


            // Simulate Dapper behavior
            var authority = new MasterData.Authority();
            fakeConnection.QueryFirstOrDefaultAsync<MasterData.Authority>(Arg.Any<string>()).ReturnsForAnyArgs(authority);

            // rest of the code
        }

在控制器中

public async Task UpdateStatus(AuthorityStatusUpdateInputDto input)
{
    
    using var connection = _dapperContextBuilder.CreateConnection();
    Authority authority = await connection.QueryFirstOrDefaultAsync<Authority>(SELECT TOP 1 * FROM Authority");

    // rest of the code
    
}

继续在

fakeConnection.QueryFirstOrDefaultAsync<MasterData.Authority>(Arg.Any<string>()).ReturnsForAnyArgs(authority);
行中获取异常

Can not return value of type Task`1 for IDbCommand.set_CommandText (expected type Void).

Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)),
and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).

If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
Return values cannot be configured for non-virtual/non-abstract members.
c# asp.net-mvc asp.net-core xunit.net nsubstitute
1个回答
0
投票

这是一个包裹

NSubstitute.Community.DbConnection

我尝试使用该包:

var connectionFactory = Substitute.For<IDapperContextBuilder>();
            var fakeConnection = Substitute.For<IDbConnection>().SetupCommands();
            
            connectionFactory.CreateConnection().Returns(fakeConnection);

            var authority1 = new Authority() { Id = 1, Name = "N1" };
            var authority2 = new Authority() { Id = 2, Name = "N2" }  ;
            
            fakeConnection.SetupQuery("SELECT * FROM Authority").Returns(authority1, authority2);

当我调试测试时:

您可以按照此包中的代码了解更多要求

© www.soinside.com 2019 - 2024. All rights reserved.