如何在N层架构中模拟实体框架

时间:2016-05-17 09:33:13

标签: entity-framework unit-testing mocking moq n-layer

我有一个带有实体框架的N层应用程序(代码优先方法)。现在我想自动化一些测试。我正在使用 Moq框架。我发现编写测试有些问题。也许我的架构错了?如果错误,我的意思是我编写的组件不是很好,因此它们不可测试。我真的不喜欢这个......或许,我根本无法正确使用moq框架。

我让你看到我的架构:

enter image description here

在每个级别,我都会在类的构造函数中注入context

门面:

public class PublicAreaFacade : IPublicAreaFacade, IDisposable
{
    private UnitOfWork _unitOfWork;

    public PublicAreaFacade(IDataContext context)
    {
        _unitOfWork = new UnitOfWork(context);
    }
}

BLL:

public abstract class BaseManager
{
    protected IDataContext Context;

    public BaseManager(IDataContext context)
    {
        this.Context = context;
    }
}

存储库:

public class Repository<TEntity>
    where TEntity : class
{
    internal PublicAreaContext _context;
    internal DbSet<TEntity> _dbSet;

    public Repository(IDataContext context)
    {
        this._context = context as PublicAreaContext;
    }
}

IDataContext是由我的DbContext实现的接口:

public partial class PublicAreaContext : DbContext, IDataContext

现在,我如何模拟EF以及如何编写测试:

[TestInitialize]
public void Init()
{
    this._mockContext = ContextHelper.CreateCompleteContext();
}

ContextHelper.CreateCompleteContext()的位置:

public static PublicAreaContext CreateCompleteContext()
{
    //Here I mock my context
    var mockContext = new Mock<PublicAreaContext>();

    //Here I mock my entities
    List<Customer> customers = new List<Customer>()
    {
        new Customer() { Code = "123455" }, //Customer with no invoice
        new Customer() { Code = "123456" }
    };

    var mockSetCustomer = ContextHelper.SetList(customers);
    mockContext.Setup(m => m.Set<Customer>()).Returns(mockSetCustomer);

    ...

    return mockContext.Object;
}

这就是我写测试的方式:

[TestMethod]
public void Success()
{
    #region Arrange
    PrepareEasyPayPaymentRequest request = new PrepareEasyPayPaymentRequest();
    request.CodiceEasyPay = "128855248542874445877";
    request.Servizio = "MyService";
    #endregion

    #region Act
    PublicAreaFacade facade = new PublicAreaFacade(this._mockContext);
    PrepareEasyPayPaymentResponse response = facade.PrepareEasyPayPayment(request);
    #endregion

    #region Assert
    Assert.IsTrue(response.Result == it.MC.WebApi.Models.ResponseDTO.ResponseResult.Success);
    #endregion
}

这里好像一切正​​常!看起来我的架构是正确的。但是,如果我想插入/更新实体怎么办?什么都没有了!我解释原因:

正如您所看到的,我将*Request对象(它是DTO)传递给了立面,然后在我的TOA中,我从DTO的属性中生成了我的实体:

private PaymentAttemptTrace CreatePaymentAttemptTraceEntity(string customerCode, int idInvoice, DateTime paymentDate)
{
    PaymentAttemptTrace trace = new PaymentAttemptTrace();
    trace.customerCode = customerCode;
    trace.InvoiceId = idInvoice;
    trace.PaymentDate = paymentDate;

    return trace;
}

PaymentAttemptTrace是我将插入实体框架的实体..它没有被嘲笑,我无法注入它。因此,即使我传递了我的模拟上下文(IDataContext),当我尝试插入一个未被模拟的实体时,我的测试失败了!

这里怀疑我有一个错误的架构已经提出来了!

那么,有什么不对?架构或我使用moq的方式?

感谢您的帮助

更新

这是我如何测试我的代码..例如,我想测试付款的跟踪..

这里测试:

[TestMethod]
public void NoPaymentDate()
{
    TracePaymentAttemptRequest request = new TracePaymentAttemptRequest();
    request.AliasTerminale = "MyTerminal";
    //...
    //I create my request object

    //You can see how I create _mockContext above
    PublicAreaFacade facade = new PublicAreaFacade(this._mockContext);
    TracePaymentAttemptResponse response = facade.TracePaymentAttempt(request);

    //My asserts
}

这里是门面:

public TracePaymentAttemptResponse TracePaymentAttempt(TracePaymentAttemptRequest request)
{
    TracePaymentAttemptResponse response = new TracePaymentAttemptResponse();

    try
    {
        ...

        _unitOfWork.PaymentsManager.SavePaymentAttemptResult(
            easyPay.CustomerCode, 
            request.CodiceTransazione,
            request.EsitoPagamento + " - " + request.DescrizioneEsitoPagamento, 
            request.Email, 
            request.AliasTerminale, 
            request.NumeroContratto, 
            easyPay.IdInvoice, 
            request.TotalePagamento,
            paymentDate);

        _unitOfWork.Commit();

        response.Result = ResponseResult.Success;
    }
    catch (Exception ex)
    {
        response.Result = ResponseResult.Fail;
        response.ResultMessage = ex.Message;
    }

    return response;
}

这是我开发PaymentsManager

的方式
public PaymentAttemptTrace SavePaymentAttemptResult(string customerCode, string transactionCode, ...)
{
    //here the problem... PaymentAttemptTrace is the entity of entity framework.. Here i do the NEW of the object.. It should be injected, but I think it would be a wrong solution
    PaymentAttemptTrace trace = new PaymentAttemptTrace();
    trace.customerCode = customerCode;
    trace.InvoiceId = idInvoice;
    trace.PaymentDate = paymentDate;
    trace.Result = result;
    trace.Email = email;
    trace.Terminal = terminal;
    trace.EasypayCode = transactionCode;
    trace.Amount = amount;
    trace.creditCardId = idCreditCard;
    trace.PaymentMethod = paymentMethod;

    Repository<PaymentAttemptTrace> repository = new Repository<PaymentAttemptTrace>(base.Context);
    repository.Insert(trace);

    return trace;
}

最后我如何编写存储库:

public class Repository<TEntity>
    where TEntity : class
{
    internal PublicAreaContext _context;
    internal DbSet<TEntity> _dbSet;

    public Repository(IDataContext context)
    {  
        //the context is mocked.. Its type is {Castle.Proxies.PublicAreaContextProxy}
        this._context = context as PublicAreaContext;
        //the entity is not mocked. Its type is {PaymentAttemptTrace} but should be {Castle.Proxies.PaymentAttemptTraceProxy}... so _dbSet result NULL
        this._dbSet = this._context.Set<TEntity>();
    }

    public virtual void Insert(TEntity entity)
    {
        //_dbSet is NULL so "Object reference not set to an instance of an object" exception is raised
        this._dbSet.Add(entity);
    }
}

4 个答案:

答案 0 :(得分:2)

您的架构看起来不错,但实施存在缺陷。它是泄漏抽象

在你的图表中,Façade图层仅取决于 BLL ,但是当你查看PublicAreaFacade的构造函数时,你会看到它实际上它有直接依赖存储库层的接口:

public PublicAreaFacade(IDataContext context)
{
    _unitOfWork = new UnitOfWork(context);
}

这不应该。它应该只将其直接依赖作为输入 - PaymentsManager或 - 甚至更好 - 它的接口:

public PublicAreaFacade(IPaymentsManager paymentsManager)
{
    ...
}

概念是您的代码变得方式更易测试。现在看一下你的测试,你会看到你必须模拟系统的最内层(即IDataContext甚至是它的实体访问器Set<TEntity>),而你要测试其中一个系统的大多数外层PublicAreaFacade类)。

如果TracePaymentAttempt仅取决于PublicAreaFacade,那么IPaymentsManager方法的单元测试就是这样的:

[TestMethod]
public void CallsPaymentManagerWithRequestDataWhenTracingPaymentAttempts()
{
    // Arrange
    var pm = new Mock<IPaymentsManager>();
    var pa = new PulicAreaFacade(pm.Object);
    var payment = new TracePaymentAttemptRequest
        {
            ...
        }

    // Act
    pa.TracePaymentAttempt(payment);

    // Assert that we call the correct method of the PaymentsManager with the data from
    // the request.
    pm.Verify(pm => pm.SavePaymentAttemptResult(
        It.IsAny<string>(), 
        payment.CodiceTransazione,
        payment.EsitoPagamento + " - " + payment.DescrizioneEsitoPagamento,
        payment.Email,
        payment.AliasTerminale,
        payment.NumeroContratto,
        It.IsAny<int>(),
        payment.TotalePagamento,
        It.IsAny<DateTime>()))
}

答案 1 :(得分:0)

IUnitOfWork传递给Facade或BLL图层构造函数,无论哪个人直接调用工作单元。然后,您可以设置Mock<IUnitOfWork>在测试中返回的内容。你不应该将IDataContext传递给除了repo构造函数和工作单元之外的所有东西。

例如,如果Facade的方法PrepareEasyPayPayment通过UnitOfWork调用进行回购调用,请按以下方式设置模拟:

// Arrange
var unitOfWork = new Mock<IUnitOfWork>();
unitOfWork.Setup(x => x.PrepareEasyPayPaymentRepoCall(request)).Returns(true);
var paymentFacade = new PaymentFacade(unitOfWork.Object);

// Act
var result = paymentFacade.PrepareEasyPayPayment(request);

然后,您已经模拟了数据调用,可以更轻松地在Facade中测试您的代码。

对于插入测试,您应该使用像CreatePayment这样的Facade方法,该方法需要PrepareEasyPayPaymentRequest。在CreatePayment方法中,它应该引用repo,可能通过工作单元,如

var result = _unitOfWork.CreatePaymentRepoCall(request);
if (result == true)
{
    // yes!
} 
else
{
    // oh no!
}

您要为单元测试模拟的是,此create / insert repo调用返回true或false,因此您可以在repo调用完成后测试代码分支。

您还可以测试插入调用是否按预期进行,但这通常没有那么有价值,除非该调用的参数在构建它们时涉及很多逻辑。

答案 2 :(得分:0)

听起来你需要稍微改变一下代码。新事物引入了硬编码的依赖关系并使它们不可测试,因此尝试将它们抽象出来。也许你可以隐藏与另一层后面的EF有关的一切,然后你要做的就是模拟那个特定的图层层,永远不要触摸EF。

答案 3 :(得分:0)

您可以使用此开源框架进行单元测试,这对模拟实体框架dbcontext

是有益的

https://effort.codeplex.com/

尝试此操作可以帮助您有效地模拟数据。