如何单元测试(在C#中)单击一个按钮? [英] How to unit test (in C#) that a button is clicked?

查看:160
本文介绍了如何单元测试(在C#中)单击一个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件,其按钮的click事件处理程序包含核心逻辑。我想测试这个按钮点击处理程序。
这个处理函数调用另一个用户控件的公共函数(它驻留在单独的C#项目中),最终调用引用程序集的public函数。
任何人都可以告诉我 - 这个处理程序的单元测试将如何?

解决方案

在单元测试中,我们测试单位 - 在这种情况下,用户控制。没什么了但是我们不应该允许用户控制访问外界,我们应该使用嘲讽技巧。
例如,如果您的UserControlA调用UserControlB,为UserControlB创建一个界面,并用模拟UserControlB替换:

  UserControlA类{
UserControlBInterface BReference;
public void setBReference(UserControlBInterface reference){this.BReference = reference};
void OnClick(...){BReference.callAMethod(); }
}
class MockupForB:UserControlBInterface {
boolean called = false;
public void callAMethod(){this.called = true; }

}
class TesterA:UnitTest {
public void testOnClick()
{UserControlA a = new UserControlA(); MockupForB模型=新的MockupForB(); a.setBReference(实体模型);
a.Button1.PerformClick(...); //跟随Aaronontheweb的建议
assertTrue(mockup.called,UserControlA不调用的方法callAMethod);
}
}

为确保UserControlB确实调用参考库,属于UserControlB的单元测试。


I have a user control that has button whose click event handler contains the core logic. I want to test this button click handler. This handler function calls a public function of another user control (which resides in separate C# project) which ultimately calls public function of a reference assembly. Can anyone please tell me - how will be the unit test for such a handler?

解决方案

In unit testing, we test the Unit - in this case, the user control. And nothing more. But we shouldn't allow the user control to access outside world, we should use mocking techniques. In example, if your UserControlA calls UserControlB, create an interface for UserControlB and replace it with a mock UserControlB :

   class UserControlA {
       UserControlBInterface BReference;
       public void setBReference(UserControlBInterface reference) { this.BReference = reference };
       void OnClick (...) { BReference.callAMethod(); }
   }
   class MockupForB : UserControlBInterface {
       boolean called=false;
       public void callAMethod() { this.called = true; }

   }
   class TesterA : UnitTest {
       public void testOnClick()
       {   UserControlA a  = new UserControlA();  MockupForB mockup = new MockupForB(); a.setBReference(mockup);
           a.Button1.PerformClick(...); //following Aaronontheweb's advice
           assertTrue(mockup.called,"the method callAMethod not being called by UserControlA");
       }
   }

And to ensure UserControlB indeed calls a reference library, this belongs to unit test for UserControlB.

这篇关于如何单元测试(在C#中)单击一个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆