简体   繁体   English

C#Rhino在第二次调用中使用硬编码参数模拟stubmethod

[英]C# Rhino mocks stubmethod with hard coded parameter in second call

This may not be something that's even possible but I thought I'd ask anyway. 这可能不是甚至可能的事情,但我想我还是会问。 Is there anyway for me to stub out this method so that the second call is also stubbed out using the parameter provided in the method I'm testing? 反正我是否存在这个方法,以便使用我正在测试的方法中提供的参数来删除第二个调用?

The method to stub: 存根的方法:

public SupportDetails GetSupportDetails(string languageKey)
{
    var result = FindSupportDetails(languageKey);

    return result ?? FindSupportDetails("en-us");
}

My Current test: 我当前的测试:

public void GetsUSDetails_IfLangKeyDoesNotExist()
{
    var langKey = "it-it";

    _repo.Stub(s => s.FindSupportDetails(langKey))
         .Return(supportDetails.Where(sd => sd.LanguageKey == langKey)
                               .SingleOrDefault());

    ISupportRepository repo = _repo;
    var actual = repo.GetSupportDetails(langKey);

    Assert.AreEqual("en-us", actual.LanguageKey);
}

and the supportDetails object used in the test: 以及测试中使用的supportDetails对象:

supportDetails = new SupportDetails[]
        {
            new SupportDetails()
            {
                ContactSupportDetailsID = 1,
                LanguageKey = "en-us"
            },
            new SupportDetails()
            {
                ContactSupportDetailsID = 2,
                LanguageKey = "en-gb"
            },
            new SupportDetails()
            {
                ContactSupportDetailsID = 3,
                LanguageKey = "es-es"
            }
        };

The correct and the most elegant solution to your problem is to use Do method: 正确和最优雅的解决方案是使用Do方法:

_repo.Stub(s => s.FindSupportDetails(null))
     .IgnoreArguments()
     .Do((Func<string, SupportDetails>) 
         (langKey => supportDetails.SingleOrDefault(sd => sd.LanguageKey == langKey)));

The Func will raise no matter what argument was passed to FindSupportDetails , then the correct SupportDetails will select. 无论将哪个参数传递给FindSupportDetailsFunc都会引发,然后选择正确的SupportDetails

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM