2013-02-18 1 views
1

Nunit 테스트를 처음 사용했습니다. 데이터베이스에 데이터를 삽입하는 메서드의 테스트 메서드를 작성하려고합니다.Nunit - 데이터 삽입 테스트 문제

내 코드와 같은 것입니다 : 내가 테스트를 실행할 때이 오류가

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using MBT.Datastore; 
using System.Data; 

using MBT.Entities; 


    public class TagStore 
{ 
    private string _connectionString = string.Empty; 

    public TagStore() 
    { 
    this._connectionString = SqlHelper.GetConnectionString(); 
    } 


    public bool InsertTag(Tag tag) 
    { 
    bool isInserted = false; 

    using (DatabaseHelper helper = Utility.DbHelper) 
    { 
     int tagsAdded = helper 
      .AddInputParameter("@Tag", tag.TagName) 
      .AddInputParameter("@ParentTagId", tag.ParentTagId) 
      .ExecuteNonQuery("Proc_InsertTags", CommandType.StoredProcedure); 

     if (tagsAdded > 0) 
     { 
      isInserted = true; 
     } 
    } 
    return isInserted; 
} 
} 

처럼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using NUnit.Framework; 
using MBT.Entities; 


[TestFixture] 
public class TagStoreTest 
{ 
    private Tag testTag; 

    public TagStoreTest() 
    { 
     this.testTag = new Tag(); 
    } 

[Test] 
public void InsertTagTest() 
{ 
    TagStore tagSt = new TagStore(); 
    bool isInserted = tagSt.InsertTag(this.testTag); 

    Assert.IsTrue(isInserted); 
} 


[SetUp] 
public void Setup() 
{ 
    this.testTag.TagName = "testtagthroughNunit"; 
} 

    [TearDown] 
    public void TearDown() 
    { 

    } 

} 

그리고 실제 TagStore 코드입니다 : TagStoreTest.InsertTagTest: System.NullReferenceException : Object reference not set to an instance of an object.

그리고 코드 라인 TagStore tagSt = new TagStore();이 빨간색으로 강조 표시됩니다 .

내 프로젝트가 성공적으로 빌드되기 때문에 나에게 무슨 일이 생길지 모르지만 테스트를 실행할 때 오류가 발생합니다.

+1

NUNIT를 실행할 때 일반적으로 스택 추적이 있습니다. 또한 SqlHelper.GetConnectionString()에는 유닛 테스트 중에 올바르게 인스턴스화하지 않는 외부 종속성이 있습니까? – Alex

답변

1

TagStore 생성자가 connectionString 멤버를 설정하고 있습니다.

SqlHelper.GetConnectionString(); 

SqlHelper가 트릭을 재생할 수 있습니다.

또한 테스트를 격리하기 위해 일종의 조롱 기술을 사용해 보는 것이 좋습니다. 예 : 항상 원하는 connectionstring을 반환하는 SqlHelper 개체를 조롱 할 수 있습니다. 예를 들어 많은 프레임 워크가 있습니다. Moq.

+0

예 .. 당신 말이 맞아 ... SqlHelper.GetConnectionString(); 단 ... 나는 stackstrace를 확인하고 또한 SqlHelper.GetConnectionString()을 가리키고있다. 그러나 적절한 연결 문자열을 얻을 수있는 디버깅 코드를 시도했을 때 ... SQLHelper의 코드는 다음과 같다 : public static string GetConnectionString() { 반환 값 System.Configuration.ConfigurationManager.ConnectionStrings [ "ConStr"]. ToString(); }, 구성 관리자 만 문제가 될 수 있지만 클래스 라이브러리에 참조가 추가되었습니다. – user1181942

+1

이것은 시험을 격리해야하는 이유입니다. 처음에는 비즈니스 코드 (TagStore)를 테스트했지만 이제는 작업을 수행중인 연결 문자열 문제를 처리하고 있습니다 (연결 문자열 문제 무시). Mock 프레임 워크 중 하나를 살펴보고이를 단위 테스트에 구현하는 것이 좋습니다. 귀하의 conneciton 객체를 모의하고 비즈니스 코드를 테스트하십시오. BusinessCode를 끝내고 나서 connectionstring으로 문제를 해결하십시오. 아이디어는 한 번에 한 가지 문제를 해결합니다 :) – daehaai