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. 単体テストで外部リソース (この場合はデータベース) に依存したくない場合。コードは問題ないかもしれませんが、このデータベースがダウンしている場合、テストは失敗する可能性があります。リポジトリ パターンのようなものを見て、接続文字列ではなくリポジトリを渡します (または、理想的にはDependency Injectionを使用して挿入します)。このアプローチを使用すると、「偽の」リポジトリを使用でき、返されるデータを完全に制御でき、データベースへの依存を削除できます。必要に応じて、リポジトリを分離してテストすることもできます。
  2. このコードは、単一責任の原則に違反しているように見えます。データ アクセスと UI の更新を担当しています。リポジトリを呼び出すと、コードからデータ アクセスが削除され、テストが容易になります。

コードがどれだけ分離されているかを示す良い指標は、テストがいかに簡単かということです。コードのテストが困難な場合は、リファクタリングの候補になる可能性があります。

于 2012-07-20T11:05:36.147 に答える