2012-03-20 29 views
3

我有一个字典,我正在使用,以避免写大if语句。它将一个枚举映射为一个动作。它看起来像这样:单元测试委托操作被称为

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) 
            }, 
          }; 

那么我这样称呼它在我的方法:

 decisionMapper[(int) reviewDecisionRequest.ReviewStepType](); 

我的问题是我怎么能单元测试这些映射? (我使用NUnit和C#4.0)

我怎么能断言,当我打电话给我的decisionMapper - 即1等于呼叫-caseDecisionService.ProcessSendStandardLetter(aCase)。

非常感谢。

+0

ReviewStepType是什么类型?枚举?如果你可以Enum.GetValues()(然后将每一个转换为int)。 – 2012-03-20 11:07:27

+0

嗨,谢谢,是它的一个枚举。这将如何与测试一起工作?我想知道我已经正确地完成了我的映射。 – Sean 2012-03-20 11:10:56

回答

1

感谢大家对此的帮助。这是我最终做的。

我嘲笑Action Service调用,然后调用字典的值,然后调用AssertWasCalled/AssertWasNotCalled。像这样:

 mapper[(int) ReviewStepType.StandardLetter].Invoke(); 
     caseDecisionService.AssertWasCalled(c => c.ProcessSendStandardLetter(aCase), 
              options => options.IgnoreArguments()); 
     caseDecisionService.AssertWasNotCalled(c => 
               c.ProcessSendBespokeLetter(aCase), 
               options => options.IgnoreArguments()); 
     caseDecisionService.AssertWasNotCalled(c => 
               c.ProcessContinueAsCase(aCase), 
               options => options.IgnoreArguments()); 
2

您无法比较匿名代表(请参阅this链接)。您必须使用一点反思来检查Action委托人的Method财产。它必须匹配应该调用的caseDecisionService方法的MethodInfo。例如(您可能改写使用功能,使短码):

MethodInfo methodToCall = 
    decisionMapper[(int)ReviewStepType.StandardLetter].Method; 

MethodInfo expectedMethod = 
    typeof(CaseDecisionService).GetType().GetMethod("ProcessSendStandardLetter"); 

Assert.AreSame(expectedMethod, methodToCall); 
+0

谢谢你。尽管“.Method”返回了映射器初始化的服务方法的methodinfo。不是特定的Action方法信息。所以此刻断言总是假的 – Sean 2012-03-20 13:53:06

+1

感谢大家的帮助。最终我得到了这样的工作。我嘲笑Action(caseDecisionService),在字典上调用Invoke,然后使用assertwascalled/assertwasnotcalled。像这样: mapper [(int)ReviewStepType.StandardLetter] .Invoke(); caseDecisionService.AssertWasCalled(c => c.ProcessSendStandardLetter(aCase),options => options.IgnoreArguments()); caseDecisionService.AssertWasNotCalled(c => c.ProcessSendBespokeRpcLetter(aCase),options => options.IgnoreArguments()); – Sean 2012-03-20 14:56:17

+0

好主意,发贴为答案! – 2012-03-20 16:21:31

1

我个人不会刻意编写单元测试,直接检查这些动作在每种情况下被调用。

假设这本词典是一个更大的系统的一部分,我会写一个测试,通过任何类别的字典行动包含字典。我想检查我的代码给我预期的结果(例如调用ProcessSendStandardLetter()ProcessSendBespokeLetter()的结果);我对检查它究竟是如何做不太感兴趣。