Unit Testing – Setup pattern (Moq)

Frank Code

In my previous post I mentioned that large unit test setups can be difficult to maintain / understand. This problem can be reduced by following a test pattern. I want to share with you a pattern I use, and I think works really well. In this post I will be using C#, Moq libary and Visual Studio test tools.

To start here are some things I believe make a good suite of unit tests:

  • Easy to identify data dependencies of tests.
  • Mocking is not repeated every test.
  • Test are clear and easy to understand / maintain.
  • New tests can be added with relative ease.

In order to explain this testing pattern I have forked my buddies TodoMVC app, and introduced a service layer, repository pattern and test project. You can see my source code with an example test class on github.

The TodoModule (service layer) has a number of public methods; Get…

View original post 315 more words

Extending mocking with Moq

Coding Journeyman

simulator

In the last part of my Dependency Injection article I introduced the term of “mocking”. This kind of test double can be really powerful. Yet in my example I had to create 2 new classes (my mocks) to be able to test my functionality in order to reduced coupling. Here is the code used by the tests:

class MockNotifier : INotifier
{public MockNotifier(){
        NotifyHasBeenCalled =false;}
 
    publicbool NotifyHasBeenCalled {get;privateset;}
 
    publicvoid Notify(User user){
        NotifyHasBeenCalled =true;}}
 
class MockRepository : IUserRepository
{publicbool HasValidatedNotification {get;set;}
 
    public User GetById(int userId){returnnew User { HasActivatedNotification = HasValidatedNotification };}}
 
[TestClass]publicclass NotificationServiceTest
{private NotificationService _notificationService;private MockNotifier _mockNotifier;private MockRepository _mockRepository

View original post 659 more words

Blog at WordPress.com.

Up ↑