UnoSD / Moq.Dapper

Moq extensions for Dapper methods.
GNU General Public License v2.0
173 stars 78 forks source link

Testing Query with string array parameter #93

Open Dev99987 opened 11 months ago

Dev99987 commented 11 months ago

Hi,

I have been trying to test one of my Dapper repository methods which uses a string array as one of it's input parameters. The method itself works great but when I run the test it fails with the following error: System.ArgumentNullException : Value cannot be null. (Parameter 'input')

By removing the array from the input parameters the error goes away. The error occurs at the Query call.

The method I'm testing:

public IEnumerable<DataModel> GetData(string[] stringarrayparameter)
{
    using var log = _logger.CurrentMethodStart();

    var sql = @"
        select * from SameTable where SameColumn IN @stringarrayparameter
    ";

    using var connection = _SqlConnectionFactory.CreateConnection();

    connection.Open();

    return connection.Query<DataModel>(sql, new { @stringarrayparameter});
}

Dapper setup:

public virtual ISqlConnectionFactory GetMockSqlConnectionFactory()
{
    var mockDbConnectionFactory = new Mock<ISqlConnectionFactory>();
    var mockDbConnection = new Mock<IDbConnection>();
    var stringarrayparameter = new[] { "value" };

    var returnValue = new[]
    {
        new ReturnValue()
        {
            a = 1,
            b = 2,
            c = 3
        }
    };

    mockDbConnection.SetupDapper(c => c.Query<DataModel>(It.IsAny<string>(), new { @stringarrayparameter }, null, true, null, null)).Returns(ReturnValue);

    mockDbConnectionFactory.Setup(x => x.CreateConnection()).Returns(mockDbConnection.Object);

    return mockDbConnectionFactory.Object;
}

The test I'm running:

[Fact]
public void Repository_GetData_Ok()
{
    #region ARRANGE

    var sqlConnectionFactory = GetMockSqlConnectionFactory();
    var logger = GetLogger<Repository>(_output);
    var stringarrayparameter = new[] { "value" };

    #endregion ARRANGE

    #region ACT

    var ctr = new Repository(logger, sqlConnectionFactory);
    var act = ctr.GetData(stringarrayparameter);

    #endregion ACT

    #region ASSERT

    var dataModels = act.ToList();
    dataModels.Should().NotBeNull();

    #endregion ASSERT
}