简体   繁体   English

如何对基于参数类型处理参数的方法进行单元测试

[英]How do I unit test a method which handles parameters based on their type

I have a method called ProcessMessage(IMessage message, IMessageHandler<IMessage> messageHandler) . 我有一个称为ProcessMessage(IMessage message, IMessageHandler<IMessage> messageHandler) The containing class has a collection of Message handlers: List<IMessageHandler<IMessage>> messageHandlers . 包含的类具有消息处理程序的集合: List<IMessageHandler<IMessage>> messageHandlers

I need to pull out a specific Message Handler from my List<IMessageHandler<IMessage>> to process any given message correctly. 我需要从List<IMessageHandler<IMessage>>拉出特定的消息处理程序,以正确处理任何给定的消息。

ProcessMessage(message, this.messageHandlers.SingleOrDefault
(
    mh => mh.GetType().GetGenericArguments()[0].GetType() == message.GetType()
));

My problem occurs when I try to unit test this function. 当我尝试对该功能进行单元测试时,会发生我的问题。 I need to populate my List<IMessageHandler<IMessage>> with mocked up message handlers. 我需要用模拟的消息处理程序填充List<IMessageHandler<IMessage>> Unfortunately, GetType() is non-virtual and I get the standard "Invalid setup on a non-virtual member" error from moq. 不幸的是,GetType()是非虚拟的,我从最小订量中得到了标准的“在非虚拟成员上的无效设置”错误。 Or a better way to setup my test data? 还是设置测试数据的更好方法?

Is there a better way to architect this so that I don't have to use a non-virtual method (ie: GetType) to do that comparison? 有没有一种更好的架构方法,这样我就不必使用非虚拟方法(即GetType)进行比较了?

You should never base your unit test on implementation details, you should test the functionality of your code instead. 永远不要以实现细节为基础进行单元测试,而应该测试代码的功能。

The fact that your code is using GetType() method is an implementation detail only. 您的代码正在使用GetType()方法这一事实仅是实现细节。 What is more important is that your code should be able to find the correct message handler for a provided message. 更重要的是,您的代码应该能够为提供的消息找到正确的消息处理程序。

To test the functionality of your code, you can create a few manual implementation of the IMessage and IMessageHandler<IMessage> interfaces. 为了测试代码的功能,您可以创建一些IMessageIMessageHandler<IMessage>接口的手动实现。 A few test cases worth covering: 一些值得介绍的测试用例:

  1. The correct message handler gets invoked 正确的消息处理程序被调用
  2. There are multiple message handlers for a certain message 某个消息有多个消息处理程序
  3. There are no message handlers for a certain message 某条消息没有消息处理程序

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

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