In General, it is difficult to test the UI composition, like how many buttons and what will the button look like. It may not have so much value that we test what are the exactly height, width and position of the compositions, but it makes sense that we can verify how many controls added to the UI and what are the content of the control. With the help of Rhino Mock and “Factory Pattern”, I can do it like this using C#:
Step 1 – Extract Interface and Introduce a UI Factory
Suppose we are going to create a commandbar for outlook, we have the code like this:
Introduce a factory and Interfaces:
Step 2 – Mock ICommandBarFactoryImpl for CommandBarFactory:
After step1’s change, we can mock ICommandBarFactoryImpl and test the commandbarFactory. I use Rhino Mock to do this:
Then I pass the mock impl to the factory:
Now, I can execute the CreateCommandBar() method and verify what I want!
Step 3 – Move all the add method to the Interface
To test how many buttons are added, we need to verify how many times the Add method has been called. A simple way to test it is to extract all the add methods into parent Interface and transformed them into create methods. In my example, it should be:
Step 4 – Writing Mock Test to Verify
Everything has been prepared and I can start the testing now!
The code would be:
In this case, we not only could verify how many times the create method has been called, which means how many buttons created, but also verify they all are added to the commandbar!