Search code examples
c#unit-testingdesign-patternsmediator

Unit Testing with the Mediator Pattern - All Private to Public


I am using the mediator pattern to facilitate unit testing of GUI objects.

psudo code Example:

Class MyGuiClass
{
  //...  Declare and initialize mediator to be a MyMediator
  private void On_SomeButtonPressed()
  {
     mediator.SomeButtonWasPressed();
  }
}

Class MyMeditator
{
  public void On_SomeButtonPressed()
  {
     //.. Do something now that the button was pressed
  }

}

This is nice because I can now unit test what happens when SomeButton is pressed without having to create a Window.

My concern is that I have taken a method that was private and made it public for any one who makes a Mediator to call. Past times I have done this it did not bother me because I did not have many methods that I had to make public.

I am currently refactoring a very large class to use this pattern and I am wondering if there is someway I can control the visibility of who can make a MyMediator or which classes some of the methods are public for. (This may not be possible or even needed, but I thought I would ask.)

(I am using C# 3.0 with .NET 3.5 SP1)


Solution

  • The point is that you'd like the public interface of a class to show that class's public 'API', so in making private methods public you are making the class more confusing and less 'clean'?

    A few things you can do: 1) think through what actually is the 'public face' of your mediator (or humble object) class and happily make those methods public. Even if they are only used within the assembly - not part of the assembly's public face - that's okay because notice that your mediator class itself is not declared public. So even its public methods are still internal to the assembly.

    2) You can fudge the privates by using internal for private (and then set the assembly's InternalsVisibleTo attribute if your test classes are in a separate assembly).

    3) Take the 'black box' approach to unit testing whereby in principle you never need to test the privates because they get tested via their use when called from the public methods.