Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 = new SupportDetails[]
        {
            new SupportDetails()
            {
                ContactSupportDetailsID = 1,
                LanguageKey = "en-us"
            },
            new SupportDetails()
            {
                ContactSupportDetailsID = 2,
                LanguageKey = "en-gb"
            },
            new SupportDetails()
            {
                ContactSupportDetailsID = 3,
                LanguageKey = "es-es"
            }
        };
like image 893
Matthew Vance Avatar asked May 25 '16 15:05

Matthew Vance


1 Answers

The correct and the most elegant solution to your problem is to use Do method:

_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.

like image 65
Old Fox Avatar answered Sep 28 '22 02:09

Old Fox