2016-05-04 9 views
0

私は単体テストに慣れています。私は自分のコードで挿入コマンドをテストする必要があります。誰でも私にそれを行う方法を教えてもらえますか?以下は私がテストしたい方法です。挿入コマンドのユニットテスト

public void InsertData() 
    {   
     Connect();  
     query = "Insert into Person values ('"+ name +"','"+ address +"','"+ 
     phn +"')";    
     cmd = new SqlCommand(query, Conn);      
     cmd.ExecuteNonQuery(); 
     DisConnect(); 
    } 
+0

あなたが読んnead:https://msdn.microsoft.com/enを-us/library/ms182532.aspx –

+0

データベースへの参照なしでインスタンスを使用する方法でテストするようにメソッドを変更する必要があります。私の知る限り、接続や切断などのメソッドとExecuteNonQueryやExecuteQueryなどのメソッドを持つコマンドインターフェイスを持つコンテキストのインターフェイスが必要です。メソッドがリファクタリングされると、メソッドをテストできます。多分あなたは依存性注入も使うべきです。 –

答えて

2

現在のところ、あなたの方法はテスト可能ではありません。実際のデータへの参照はすべて避けてください。

これは、リファクタリング方法のようになります。

public interface IDbContext 
{ 
    void Connect(); 
    void DisConnect(); 
    IDbCommand GetDbCommand(string query, string[] parameters); 
} 

public class DbContext : IDbContext 
{ 
    public IDbConnection Conn { get; set; } 

    public void Connect() 
    { 
     // your code here 
    } 

    public void DisConnect() 
    { 
     // your code here 
    } 

    public IDbCommand GetDbCommand(string query, string[] parameters) 
    { 
     // parameter handling 
     return new SqlCommand(query, (SqlConnection)Conn); 
    } 
} 

public class YourClass 
{ 
    private string name; 
    private string address; 
    private string phn; 

    public void InsertData(IDbContext context) 
    { 
     context.Connect(); 
     var cmd = context.GetDbCommand("Insert into Person values ('{0}','{1}','{2}')", new string[] { name, address, phn }); 
     cmd.ExecuteNonQuery(); 
     context.DisConnect(); 
    } 
} 

あなたは、このメソッドのようにそれを行うことができます。このテストするには:

[TestClass] 
public class TestClass 
{ 
    [TestMethod] 
    public void TestMethod1() 
    { 
     var instance = new YourClass(); 

     // create an instance of IDbContext 
     var context = new Mock<IDbContext>(); 
     // create an instance of IDbCommand 
     var command = new Mock<IDbCommand>(); 

     // setup your context and what should be the return of any method you want 
     context.Setup(c => c.GetDbCommand(It.IsAny<string>(), It.IsAny<string[]>())).Returns(command.Object); 

     // call your method you want to test 
     instance.InsertData(context.Object); 

     // assert that context methods ar called 
     context.Verify(c => c.Connect(), Times.Once); 
     context.Verify(c => c.DisConnect(), Times.Once); 
     context.Verify(c => c.GetDbCommand(It.IsAny<string>(), It.IsAny<string[]>()), Times.Once); 

     // assert that command methods ar called 
     command.Verify(c => c.ExecuteNonQuery(), Times.Once); 
    } 
}