前提・実現したいこと
・DB接続を使用したユニットテストを行いたい
発生している問題・エラーメッセージ
初めて質問いたします。
現在VisualStudioを使用しプログラミング研修を行っています。
DAOを作成し正常系のテストを実施したのですが、DB接続の部分で失敗してしまいます。
他クラスではDB接続はできていたため、文法の間違いはないかと思います。
ユニットテストではDB接続はできない仕様なのでしょうか。
開発環境
OS:Windows10
ツール:
・ASP.NET
・Visual Studio 2017
・SQL Server 2014
該当のソースコード
/// <summary> /// ID重複確認用メソッド /// </summary> /// <pre> /// 引数としてint型IDを受け取り、SQLサーバーに検索をかける /// IDの重複がなければ、0を返し、重複があれば1を返す /// </pre> /// <param name="id"></param> /// <returns></returns> public int CountByPrimaryKey(int id) { int cnt = 0; try { using (SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["DB"].ConnectionString)) { conn.Open(); //sql文 StringBuilder sb = new StringBuilder(); sb.Append("SELECT COUNT(*)AS CNT FROM dbo.USER_MASTER WHERE ID = @Id"); SqlCommand sql = null; SqlDataReader reader = null; try { if (Logger.IsDebugEnabled) { Logger.Debug(sb.ToString()); } sql = new SqlCommand(sb.ToString(), conn); sql.Parameters.AddWithValue("@Id", id); if (Logger.IsDebugEnabled) { Logger.Debug(sb.ToString()); } reader = sql.ExecuteReader(); reader.Read(); cnt = reader.FieldCount; } catch (Exception e) { Logger.Fatal(e); throw new Exception(); } } } catch(Exception e) { Logger.Fatal(e); throw new Exception(); } return cnt; }
テストコード
[TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { DataAccessObject test = new DataAccessObject(); int id = 1; int i = test.CountByPrimaryKey(id); Assert.AreEqual(i, 0); } }
エラーメッセージ
System.NullReferenceException: 'オブジェクト参照がオブジェクト インスタンスに設定されていません。'
System.Configuration.ConnectionStringSettingsCollection.this[string].get が null を返しました。
システム構成
ソリューション'MyStudy.net'
|
|
|---Step2(プロジェクト)
| ・DataAccessObject.cs
| ・Web.config
|
|---Step2Test(テストプロジェクト)
| ・UnitTest1.cs
回答3件
あなたの回答
tips
プレビュー