C#存储过程方法的单元测试

时间:2016-01-29 06:06:39

标签: c# unit-testing stored-procedures

我使用企业库来执行数据操作,而不是实体框架。

以下是我的样本BL方法,用于更新人文化。 我不知道如何为这些方法编写单元测试。

public static Culture UpdatePersonCulture(Guid userId, Culture culture)
{
    try
    {
        if (userId == Guid.Empty)
            throw new exception("User id should not be empty");

        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        Database database = factory.CreateDefault();

        using (DbConnection dbConnection = database.CreateConnection())
        {
            if (dbConnection.State == ConnectionState.Closed)
                dbConnection.Open();

            DbCommand dbCommand = database.GetStoredProcCommand("usp_UpdatePersonCulture");
            database.DiscoverParameters(dbCommand);
            dbCommand.Parameters["@userId"].Value = userId;
            dbCommand.Parameters["@cultureId"].Value = culture.Id;

            DataSet dataSet = database.ExecuteDataSet(dbCommand);

            return BLDataPopulation.PopulateCultures(dataSet.Tables[0]).FirstOrDefault();
        }
    }
    catch (Exception exception)
    {
        throw BLLogger.Log(exception);
    }
}

1 个答案:

答案 0 :(得分:4)

Change your classes to be unit test-able

单元测试意味着给定输入,我的代码将以已知行为运行并产生已知的预先输出。它应该快速执行,因为它经常执行(甚至可以在代码像NCrunch一样改变时执行)。单元测试范围应该是一个类。

Integration tests是您在更高范围内测试的测试。您可以测试几个类,一部分程序,甚至不同的程序是否能很好地协同工作。然而,这些测试的稳定性(因为它可能依赖于可能不时失效的外部组件),“工作良好”的定义仍然最为模糊,以及此类测试的维护成本,使得附加价值增加集成测试真的很低。实际上,由于维护成本的原因,我经常看到没有任何项目甚至集成测试退役的项目。

但是,您可以将不可测试的代码限制为最小值:

  • 与实现分离的接口:隔离隐藏实现复杂性的接口后面的外部资源(如文件I / O或数据库)访问。

  • 避免使用静态代码,因为无法对静态代码进行单元测试。使用静态类来实现实现。如果静态代码调用外部资源,则无法控制输入和输出,因此无法测试结果。

  • 学习重构:如果您具备相关技能,则可以轻松处理旧版代码。隔离一小段代码,为其编写单元测试,并用更强大的代码替换它。

  • Test first or Test driven development, TDD可以使新编写的代码从一开始就可以测试。这是一个过程,包括在编写类的实现之前编写对给定类的期望。

  • Behavior driven development or BDD :有时当您在购物篮中所有产品都是客户要求时,您无法轻松达到单元测试所需的最低级别。您可以使用Specflow之类的工具来构建需求语法并将其转换为测试。

为了成功编写单元测试并重构您的遗留不可测试代码,您需要IOC工具(因为构造函数签名具有使用这些技术增长的趋势)和模拟框架(如Moq)以模拟接口您将添加而不将它们绑定到任何实现。

例如,在您的情况下,我重构了包含要测试的方法的类:

public class ClassToTest : IInterfaceToTest
{
    private readonly IBLLogger _logger;
    private readonly IBLDataPopulation _blDataPopulation;
    private readonly IDatabase _database;

    public ClassToTest(IBLLogger logger, IBLDataPopulation blDataPopulation, IDatabase database)
    {
        _logger = logger;
        _blDataPopulation = blDataPopulation;
        _database = database;
    }

    // this cannot be static if you want
    // to unit test the classes depending on this one.
    public Culture UpdatePersonCulture(Guid userId, Culture culture)
    {
        try
        {
            if (userId == Guid.Empty)
                throw new Exception("User id should not be empty");

            var dataSet = _database.ProvideCultureMappings(userId, culture); 

            return _blDataPopulation.PopulateCultures(dataSet.Tables[0]).FirstOrDefault();

        }
        catch (Exception exception)
        {
            throw _logger.Log(exception);
        }
    }
}

我添加的界面:

public interface IDatabase
{
    DataSet ProvideCultureMappings(Guid userId, Culture culture);
}

public interface IBLLogger
{
    Exception Log(Exception exception);
}

public interface IBLDataPopulation
{
    IEnumerable<Culture> PopulateCultures(DataTable dataTable);
}

结果:

[TestFixture]
public class DatabaseUnitTest
{
    [Test]
    public void Test()
    {
        var logger = new Mock<IBLLogger>(MockBehavior.Strict);
        var blDataPopulation = new Mock<IBLDataPopulation>(MockBehavior.Strict);
        var database = new Mock<IDatabase>(MockBehavior.Strict);
        var toTest = new ClassToTest(logger.Object, blDataPopulation.Object, database.Object);
        var userId = Guid.NewGuid();
        var culture = new Culture{Id = "MyId"};
        var dataSet = new DataSet();
        var table = new DataTable();
        dataSet.Tables.Add(table);
        database.Setup(x => x.ProvideCultureMappings(userId, culture)).Returns(dataSet);
        var cultureList = new List<Culture> {culture, new Culture {Id = "AnotherCulture"}};
        blDataPopulation.Setup(x => x.PopulateCultures(table)).Returns(cultureList);
        var result = toTest.UpdatePersonCulture(userId, culture);
        Assert.AreEqual(result.Id, culture.Id);
    }
}

作为不可测试类的奖励:

public class Database : IDatabase
{
    public DataSet ProvideCultureMappings(Guid userId, Culture culture)
    {

        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        Database database = factory.CreateDefault();

        using (DbConnection dbConnection = database.CreateConnection())
        {
            if (dbConnection.State == ConnectionState.Closed)
                dbConnection.Open();

            DbCommand dbCommand = database.GetStoredProcCommand("usp_UpdatePersonCulture");
            database.DiscoverParameters(dbCommand);
            dbCommand.Parameters["@userId"].Value = userId;
            dbCommand.Parameters["@cultureId"].Value = culture.Id;

            DataSet dataSet = database.ExecuteDataSet(dbCommand);
            return dataSet;
        }
    }

    private DataSet ExecuteDataSet(DbCommand dbCommand)
    {
        throw new NotImplementedException();
    }

    private void DiscoverParameters(DbCommand dbCommand)
    {
        throw new NotImplementedException();
    }

    private DbCommand GetStoredProcCommand(string uspUpdatepersonculture)
    {
        throw new NotImplementedException();
    }

    private DbConnection CreateConnection()
    {
        throw new NotImplementedException();
    }
}