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

后端 未结 2 1851
小蘑菇
小蘑菇 2021-01-22 12:23

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

2条回答
  •  别那么骄傲
    2021-01-22 13:08

    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.

提交回复
热议问题