How to unit test (in C#) that a button is clicked?

假如想象 提交于 2019-12-02 05:15:19

问题


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?


回答1:


You can write a method that programmatically raises the Click event and call that from your unit test.

Edit: Ah, this actually exists already: http://msdn.microsoft.com/en-us/library/hkkb40tf(VS.90).aspx




回答2:


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.



来源:https://stackoverflow.com/questions/4436207/how-to-unit-test-in-c-that-a-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!