2016-07-15 4 views
2

Entity Framework를 사용중인 프로젝트에서 단위 테스트에 ms 단위 테스트를 사용하고 있습니다. 나는 Msdn 에서 다음 예제를 사용하여 조롱 수 있어요 그러나 나는 다음과 같은 방법단위 테스트 프레임 워크가있는 단위 테스 트 엔터티 프레임 워크

Var tran = testdbcontext.Database.BeginTransaction() 

에서 엔티티 프레임 워크 에서 트랜잭션을 사용해야하고, 테스트가 실패 곳 데이터베이스 testdbcontext에 대한 null 인 나는이 시나리오를 . 우리는 당신이 그들이 DbContext를 추상화 한 것을 볼 참조 링크 MSDN 문서를 사용하여이 작업

답변

1

를 얻기 위해 어떻게 든 조롱 할 수있는 경우

궁금입니다. 동일한 생각을 사용하여 거래 생성을 추상화해야합니다.

먼저 트랜잭션 개체에 대해 예상되는 기능의 추상화를 만듭니다.

/// <summary> 
/// Wraps access to the transaction object on the underlying store connection 
/// </summary> 
public interface IDbContextTransaction : IDisposable { 
    /// <summary> 
    /// Commits the underlying store transaction 
    /// </summary> 
    void Commit(); 
    /// <summary> 
    /// Rolls back the underlying store transaction 
    /// </summary> 
    void Rollback(); 
} 

데이터베이스 트랜잭션에서 원하는 기능을 미러링합니다.

프로덕션에서는 사용하려는 실제 개체를 래핑하는 이와 같은 구현을 가질 수 있습니다.

public class DbContextTransactionWrapper : IDbContextTransaction { 
    private DbContextTransaction dbContextTransaction; 

    public DbContextTransactionWrapper(DbContextTransaction dbContextTransaction) { 
     this.dbContextTransaction = dbContextTransaction; 
    } 

    public void Commit() { 
     dbContextTransaction.Commit(); 
    } 

    public void Rollback() { 
     dbContextTransaction.Rollback(); 
    } 

    public void Dispose() { 
     if(dbContextTransaction != null) { 
      dbContextTransaction.Dispose(); 
      dbContextTransaction = null; 
     } 
    } 
} 

DbContext 추상화는 트랜잭션을 생성 할 수있는 기능 ...

public interface IStoreAppContext : IDisposable { 
    DbSet<Product> Products { get; } 
    int SaveChanges(); 
    void MarkAsModified(Product item); 
    IDbContextTransaction BeginTransaction(); 
} 

을 포함 할 것입니다 및 구현 단위 테스트에서, 래퍼

public class StoreAppContext : DbContext, IStoreAppContext 
{ 
    public StoreAppContext() : base("name=StoreAppContext") 
    { 
    } 

    public DbSet<Product> Products { get; set; } 

    public void MarkAsModified(Product item) 
    { 
     Entry(item).State = EntityState.Modified; 
    } 

    public IDbContextTransaction BeginTransaction() { 
     return new DbContextTransactionWrapper(Database.BeginTransaction()); 
    } 
} 

에게 그 방법을 사용하는 것이 수행 할 수 있습니다 조롱 프레임 워크 또는 가짜 구현을 통해 트랜잭션 생성을 조롱하면 추상화 된 DbContext에서 직접 호출 할 수 있습니다. 가정 testdbcontext

IDbContextTransaction tran = testdbcontext.BeginTransaction(); 

이 당신이 인터페이스에 정의 된 tran.Commit()tran.Rollback()에 대한 액세스를 쉽게 테스트 할 수 할 줄 것이다 ... 유형 IStoreAppContext 다음 호출의 모습이다.

+0

감사합니다. – Vivekh

+0

커밋() 코드는 무엇이되어야합니까? – Vivekh

+0

트랜잭션에 커밋하는 데 사용 된 Completed() 메서드가 있습니다. – Nkosi

관련 문제