简体   繁体   English

在EventHandler中对发送方对象进行单元测试

[英]Unit Testing the sender object in EventHandler

Lets say I have a eventhandler like so: 可以说我有一个像这样的事件处理程序:

public SomethingHappended_Handler(object sender, EventArgs e)
{
  var myobj = sender as MyClass();
  myobj.DoSomethingImportant();
}

How can I test that myObj is the type of MyClass? 如何测试myObj是MyClass的类型? I know that the sender will always be of MyClass but I just thought to be safe I would need a: 我知道发件人永远是MyClass,但我只是想安全起见,我需要:

if (myObj != null) //Close it

If the type is not MyClass then myObj will be null. 如果类型不是MyClass,则myObj将为null。 As I know its best to test for the not null how can I create a unit test to prove that if I send a different type as the sender other than MyClass it will fall over calling DoSomethingImportant and therefore I need the null check? 据我所知,最好测试非空值,如何创建一个单元测试来证明,如果我以MyClass以外的其他类型发送作为发送方的数据,它将导致调用DoSomethingImportant失败,因此我需要进行空值检查吗?

I can answer you in pseudo-code to point out what you could do. 我可以用伪代码回答您,指出您可以做什么。

First off you can check if sender is of type MyClass. 首先,您可以检查发件人是否为MyClass类型。

if(sender is MyClass)

Then in your unittest you can send in two mock objects, one of type MyClass and one of another type "MyClassFake". 然后,在单元测试中,您可以发送两个模拟对象,一个是MyClass类型的对象,另一个是“ MyClassFake”类型的对象。 Make an interface both use and make them implement the Close() method. 使接口都使用并使其实现Close()方法。

Make two unittests: 进行两个单元测试:

  1. Validate that MyClass.Close() is called. 验证是否调用了MyClass.Close()。
  2. Validate that MyClassFake.Close() is never called. 验证从未调用MyClassFake.Close()。

Close() is just an example, if you have other methods, you can test called/not called against them. Close()只是一个示例,如果您有其他方法,则可以针对它们测试被调用/未被调用。

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

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