5

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

我让你看看我的架构:

在此处输入图像描述

在每个级别,我都将我的注入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),当我尝试插入一个未模拟的实体时,我的测试也会失败!

这里有人怀疑我有一个错误的架构!

那么,怎么了?我使用最小起订量的架构或方式?

谢谢你的帮助

更新

这里我如何测试我的代码..例如,我想测试支付的痕迹..

这里是测试:

[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

4 回答 4

2

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

在您的图中,Façade层仅依赖于BLL,但是当您查看PublicAreaFacade的构造函数时,您会发现实际上它直接依赖于来自Repository层的接口:

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

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

public PublicAreaFacade(IPaymentsManager paymentsManager)
{
    ...
}

结果是您的代码变得更加可测试。当您现在查看您的测试时,您会发现您必须模拟系统的最内层(即IDataContext,甚至它的实体访问器Set<TEntity>),尽管您正在测试系统的最外层之一(PublicAreaFacade类)。

如果仅依赖于,这就是该方法的单元测试的TracePaymentAttempt样子:PublicAreaFacadeIPaymentsManager

[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>()))
}
于 2016-05-26T08:45:21.923 回答
0

听起来您需要稍微更改代码。新事物引入了硬编码的依赖关系并使它们无法测试,因此请尝试将它们抽象掉。也许您可以将与 EF 相关的所有内容隐藏在另一层后面,那么您所要做的就是模拟该特定层,并且永远不要接触 EF。

于 2016-05-26T08:39:44.040 回答
0

传入FacadeIUnitOfWork或 BLL 层构造函数,无论哪一个直接调用工作单元。然后您可以设置Mock<IUnitOfWork>测试中返回的内容。IDataContext除了 repo 构造函数和工作单元之外,您不需要传递所有内容。

例如,如果 Facade 有一个PrepareEasyPayPayment通过调用进行 repo 调用的方法,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 中测试您的代码。

对于插入测试,您应该有一个 Facade 方法CreatePayment,例如需要一个PrepareEasyPayPaymentRequest. 在该CreatePayment方法中,它应该引用 repo,可能是通过工作单元,比如

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

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

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

于 2016-05-21T18:58:46.930 回答
0

您可以使用这个开源框架进行单元测试,它可以很好地模拟实体框架 dbcontext

https://efort.codeplex.com/

试试这个将帮助你有效地模拟你的数据。

于 2016-05-26T09:12:31.100 回答