0

I have the following method and want to write shim for the needed functionalities in it include ExecuteReaderAsync:

public async Task<IEnumerable<ApplicationSetting>> LoadSettingsAsync(string[] keys)
{
    await using var sourceConnection = new SqlConnection(_options.Value.StoreConnectionString);
    await sourceConnection.OpenAsync();

    SqlCommand command =
        new SqlCommand(
            SqlStatements.SelectMultipleKeys(_options.Value.DefaultStoreTableName,
                _options.Value.DefaultStoreSchema), sourceConnection);
    command.AddArrayParameters(ColumnNames.Keys, keys);
    var reader = await command.ExecuteReaderAsync();

    List<ApplicationSetting> settings = new();
    while (await reader.ReadAsync())
        settings.Add(new ApplicationSetting(reader[ColumnNames.Key].ToString()!,
            reader[ColumnNames.Value].ToString(), reader[ColumnNames.Type].ToString()!));

    await reader.CloseAsync();
    await sourceConnection.CloseAsync();
    return settings;
}

Test Method:

[Fact]
public async Task LoadSettingsAsync_WhenCall_LoadApplicationSettings()
{
    using (ShimsContext.Create())
    {
        // Arrange
        var keys = new string[] { "key1", "key2" };

        // simulate a connection
        ShimSqlConnection.AllInstances.OpenAsyncCancellationToken = (connection, token) =>
        {
            return Task.FromResult(true);
        };
        //string commandText;

        // shim-Mock all called methods
        ShimSqlCommand.AllInstances.ExecuteReaderAsync = command =>
        {
            return Task.FromResult(???????????????????????);
        };
        var rowCounter = 0;
        ShimSqlDataReader.AllInstances.Read = (sender) =>
        {
            rowCounter++;
            return rowCounter <= 2;
        };

        ShimSqlConnection.AllInstances.Close = connection => { };

        // Act
        var ex = await Record.ExceptionAsync(() =>
            _myClass.LoadSettingsAsync(keys));

        // Assert
        ex.Should().BeNull();
    }
} 

I tried Substitute.For<SqlDataReader>() to create an instance SqlDataReader but it throws System.InvalidOperationException

Then I tried this code:

ShimSqlCommand.AllInstances.ExecuteReaderAsync = async command =>
{
     return new ShimSqlDataReader();
};

But it throw NullReferenceException on await reader.ReadAsync() line (note: reader has value): enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.