Wednesday, March 12, 2025

unit assessments – The best way to write shim for ExecuteReaderAsync?


I’ve the next methodology and wish to write shim for the wanted functionalities in it embody ExecuteReaderAsync:

public async Process> LoadSettingsAsync(string[] keys)
{
    await utilizing var sourceConnection = new SqlConnection(_options.Worth.StoreConnectionString);
    await sourceConnection.OpenAsync();

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

    Checklist settings = new();
    whereas (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;
}

Take a look at Methodology:

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

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

        // shim-Mock all referred to as strategies
        ShimSqlCommand.AllInstances.ExecuteReaderAsync = command =>
        {
            return Process.FromResult(???????????????????????);
        };
        var rowCounter = 0;
        ShimSqlDataReader.AllInstances.Learn = (sender) =>
        {
            rowCounter++;
            return rowCounter <= 2;
        };

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

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

        // Assert
        ex.Ought to().BeNull();
    }
} 

I attempted Substitute.For() to create an occasion SqlDataReader nevertheless it throws System.InvalidOperationException

Then I attempted this code:

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

However it throw NullReferenceException on await reader.ReadAsync() line (notice: reader has worth):

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com