I have a Dictionary that I am using to avoid writing big if statements. It maps an enum to an action. It looks like this:
var decisionMapper = new Dictionary<int, Action>
{
{
(int) ReviewStepType.StandardLetter,
() =>
caseDecisionService.ProcessSendStandardLetter(aCase)
},
{
(int) ReviewStepType.LetterWithComment,
() =>
caseDecisionService.ProcessSendStandardLetter(aCase)
},
{
(int) ReviewStepType.BespokeLetter,
() =>
caseDecisionService.ProcessSendBespokeLetter(aCase)
},
{
(int) ReviewStepType.AssignToCaseManager,
() =>
caseDecisionService.ProcessContinueAsCase(aCase)
},
};
then I call it like this in my method:
decisionMapper[(int) reviewDecisionRequest.ReviewStepType]();
My question is how can I unit test these mappings? (I am using Nunit and c# 4.0)
How can I assert that when I call my decisionMapper - that 1 is equal to the call -caseDecisionService.ProcessSendStandardLetter(aCase).
Thanks very much.
You can't compare anonymous delegates (see this link). You have to use a little bit of reflection to check the Method property of the Action delegate. It has to match the MethodInfo of the caseDecisionService method that should be invoked. For example (You may rewrite to use a function to make code shorter):
MethodInfo methodToCall =
decisionMapper[(int)ReviewStepType.StandardLetter].Method;
MethodInfo expectedMethod =
typeof(CaseDecisionService).GetType().GetMethod("ProcessSendStandardLetter");
Assert.AreSame(expectedMethod, methodToCall);
I personally wouldn't bother writing a unit test which directly checks which action is invoked in each case.
Assuming this dictionary is part of a larger system, I'd write one test which goes through each of the Dictionary actions via whatever class contains the Dictionary. I want to check my code gives me outcomes I expect (the outcome of calling ProcessSendStandardLetter() or ProcessSendBespokeLetter(), for example); I'm less interested in checking exactly how it does it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With