【问题标题】:When to use Mock's Callback versus Return?何时使用模拟回调与返回?
【发布时间】:2012-01-13 05:01:09
【问题描述】:

我认为,我有一个非常简单的设置,其中创建了一个搜索类型,并通过服务层传递到一个返回域类型列表的存储库中。搜索类型只是在存储库方法中构造一个表达式树,基本上从数据库中返回结果。很简单

仓库界面:

public interface IDoNotSolicitRepo 
{
    IList<DNSContract> SelectWithCriteria(DNS_Search searchriteria); 
}

实现存储库的服务:

public class DoNotSolicitService : BaseBLLService, IDoNotSolicitService
{
    private readonly IDoNotSolicitRepo repo;
    private readonly IPartnerService partnerService;
    private readonly IDoNotSolicitReasonService dnsReasonSvc;
    public DoNotSolicitService(IDoNotSolicitRepo _repo, IPartnerService _partnerSvc, IDoNotSolicitReasonService _dnsReasonSvc)
    {
        repo = _repo;
        partnerService = _partnerSvc;
        dnsReasonSvc = _dnsReasonSvc;
    }

    public ServiceResult<DNSContract> SelectWithCriteria(DNS_Search searchriteria)
    {
        var results = repo.SelectWithCriteria(searchriteria);

        return ReturnServiceResult(results);
    }
}

我正在通过这个项目学习最小起订量,但我不知道我应该使用 Callback() 还是 Return()。我得到了两者的总体观点,但目前似乎都不适用于我。

测试:

[Test]
public void SelectWithCriteria_FirstName()
{
    mockRepository.Setup(mr => mr.SelectWithCriteria(It.IsAny<DNS_Search>()))
        .Returns((IList<DNSContract> records) => new List<DNSContract>
                                                     {
                                                         new DNSContract {FirstName = "unit", LastName = "test"},
                                                         new DNSContract {FirstName = "moq", LastName = "setup"}
                                                     });

    dnsSvc = new DoNotSolicitService(mockRepository.Object, new PartnerServiceStub(), new DoNotSoicitReasonServiceStub());

    var result = dnsSvc.SelectWithCriteria(new DNS_Search { FirstName = "unit" });

    Assert.IsNotNull(result);
    Assert.IsTrue(result.Data.Any());
}

错误:

System.ArgumentException was unhandled by user code


 Message=Object of type 'EP.Rest.Common.RestHelpers.DNS_Search' cannot be converted to type 'System.Collections.Generic.IList`1[EP.Rest.Domain.Contracts.DNSContract]'.

现在,我读到 Returns() 方法返回传入的类型,所以我可以看到这是导致该错误的原因。但在现实世界中,我希望返回不同的类型。我试图创建一个回调委托,但感觉都不对。

【问题讨论】:

  • 在看这个时,也许我已经违反了 stub v. fake v. mock 职责,但我仍然对 Callback 或 Return 感到模糊。
  • 查看this question 接受的答案,应该会给你一个很好的主意。他还链接到 Moq 的文档,进一步解释它。
  • 是的,我一直盯着那个帖子看了一会儿,并尝试实现链接到The Untitled Blog 的回调示例,但它只是没有点击我。看起来该博客文章与我想要的很接近,但我仍然输入一种类型(列表)。
  • @BryanGrimes,我在引用的问题上发布了一个回调示例,也许这会有所帮助。

标签: c# unit-testing moq


【解决方案1】:

只需将 lambda 放在 .Returns 上,即

.Returns(new List<DNSContract>());

您的原始方法是将参数从您的方法传递给返回以参数化结果,例如,如果从可以根据输入返回不同数据的源中提取。

或者

.Returns<IList<DNSContract>>(new List<DNSContract>(){...});

【讨论】:

  • 你刚刚拯救了我的视力和理智。看起来我仍然需要挖掘为什么这不能是回调,但我的测试有效,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多