如何写参数null异常和无效异常?

时间:2013-12-02 04:28:20

标签: c# unit-testing testing exception-handling nunit

我正在尝试为Register CommandHandler编写一个类

public virtual void RegisterCommandHandler<T>(string messageType, Action<T, MetaData> handler)
    {
        _handlers.Add(messageType, (command, metadata) => handler((T)command, metadata));

    }

我想处理两个例外:

  1. handler null exception
  2. 无效的处理程序异常
  3. 我尝试按照以下方式进行操作。但这并不成功

     if (string.IsNullOrEmpty(handler.ToString())) 
           throw new ArgumentNullException("NullException","null value");
    

    请帮我写一些验证 谢谢!

1 个答案:

答案 0 :(得分:1)

您应该检查处理程序是否直接为空。

if (handler == null)
    throw new ArgumentNullException("handler cannot be null", "handler");

你现在遇到问题的原因是如果handler为null,handler.ToString()将抛出NullReferenceException。

相关问题