Microsoft Fakes (Shims and / or Stubs) on a c# method with SQL code

╄→гoц情女王★ 提交于 2019-12-23 17:15:20

问题


I am trying to learn a bit more about Unit Testing, using out-of-the-box functionality (i believe it is MSTest.exe), and Microsoft Fakes (stubs and Shims).

I am using Visual Studio 2012 Ultimate and .Net 4.5 Framework.

Given the following code that calls a stored procedure (SQL Server) which returns a single output value (for simplicity):

public string GetSomeDatabaseValue()
{
    string someValue = String.Empty;

    SqlParameter paramater = new SqlParameter();
    paramater.ParameterName = "@SomeParameter";
    paramater.Direction = ParameterDirection.Output;
    paramater.SqlDbType = SqlDbType.NVarChar;
    paramater.Size = 50;  

    try
    {
        using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = connection;
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.CommandText = "SomeStoredProcedure";
                command.Parameters.Add(paramater);

                connection.Open();
                command.ExecuteNonQuery();

                if (command.Parameters["@SomeParameter"] != null)
                {
                    someValue= Convert.ToString(command.Parameters["@SomeParameter"].Value);
                }
            }
        }
    }
    catch(SqlException)
    {
        throw;
    }

    return someValue;
}
  1. Can it be tested using shims and/or stubs so that the output value can be set to a specific value?
  2. If so how?
  3. Should I even use unit testing for this?

I have followed this tutorial and managed to understand and adapt it to the day of the week.

I'm waiting on the VS2012 database unit tests functionality to become available by end of 2012 (or reinstated) as a MS employee has commented so that the database can be tested in isolation.


回答1:


Microsoft Fakes is not an appropriate tool to test this code. Create an integration test instead. In this test, use a local instance of the SQL server, explicitly create data that the stored procedure expects to find in the database, call the stored procedure and verify its result. Rollback transaction or manually delete data from the database to ensure that it does not affect other tests.



来源:https://stackoverflow.com/questions/13419883/microsoft-fakes-shims-and-or-stubs-on-a-c-sharp-method-with-sql-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!