0

显然,我一直在努力测试由我的团队中的开发人员构建的应用程序。类:Apis,从用户读取连接字符串、id 和错误消息。我返回值名称和资格权重的字典。因为我是测试中的新手,我面临很多问题,以使我的测试按预期工作。请告知在哪里我没有做错。
班级:

 public class Apis
{

    public Dictionary<String, String> getQualWeight(String sqlConStr, String inBin, Label lblResults)
    {
        Dictionary<String, String> qualList = new Dictionary<string, string>();
        string selectSQL = "select Name,qual_weight from Qualification_type "
                            + "where ID in (select Qualification_ID from Qualifications where BIN = @inBin)";
        con = getConn(sqlConStr);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        cmd.Parameters.AddWithValue("@inBin", inBin);
        SqlDataReader reader;
        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                qualList.Add(reader[0].ToString(), reader[1].ToString());
            }
            reader.Close();
            return qualList;
        }
        catch (Exception err)
        {
            lblResults.Text = "error fetching qualification weight " + err.Message;
            return null;
        }
        finally
        {
            con.Close();
        }
    }    

我的测试:

[TestMethod()]
    public void getQualWeightTest()
    {
        Api target = new Api();
        string sqlConStr = "SERVER=ABC123; Database=DB; UID=id; PWD=passme;encrypt=no;enlist=false";
        string inBin = "2012-52-456"; 
        Label lblResults = null;

        lblResults.Text = " Failed";
        Dictionary<string, string> expected = new Dictionary<string,string>();
        expected.Add("Gohn", "50");
        Dictionary<string, string> actual;
        actual = target.getQualWeight(sqlConStr, inBin, lblResults);
        Assert.AreEqual(expected, actual);

    }
4

1 回答 1

2

看看你的代码,我有几个建议。

  1. You don't want to rely on an external resource (in this case the Database) in your unit tests. Your code could be fine but the test could fail if this database is down. Look at something like the Repository Pattern and pass in (or ideally inject using Dependency Injection) a repository rather than a connection string. Using this approach you can use a 'Fake' repository and you have complete control over the data being passed back and you remove the dependency on the database. You can also test your repository in isolation if need be.
  2. This code looks like it is in violation of the Single Responsibility Principle, it is responsible for Data Access and updating the UI. Calling out to a repository would remove the data access from the code and make it easier to test.

我找到了一个很好的指标,说明您的代码的解耦程度以及测试的容易程度。如果您在测试代码时遇到困难,它可能是重构的候选者。

于 2012-07-20T11:05:36.147 回答