를 얻기 위해 어떻게 든 조롱 할 수있는 경우
궁금입니다. 동일한 생각을 사용하여 거래 생성을 추상화해야합니다.
먼저 트랜잭션 개체에 대해 예상되는 기능의 추상화를 만듭니다.
/// <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
다음 호출의 모습이다.
감사합니다. – Vivekh
커밋() 코드는 무엇이되어야합니까? – Vivekh
트랜잭션에 커밋하는 데 사용 된 Completed() 메서드가 있습니다. – Nkosi