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

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

问题描述

我有一个带有按钮的用户控件,其点击事件处理程序包含核心逻辑.我想测试这个按钮点击处理程序.此处理函数调用另一个用户控件(位于单独的 C# 项目中)的公共函数,最终调用参考程序集的公共函数.谁能告诉我 - 这样一个处理程序的单元测试将如何?

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?

推荐答案

在单元测试中,我们测试单元——在这种情况下,是用户控件.仅此而已.但是我们不应该让用户控件访问外部世界,我们应该使用模拟技术.例如,如果您的 UserControlA 调用 UserControlB,则为 UserControlB 创建一个接口并将其替换为模拟 UserControlB:

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

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

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

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

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