Alex Rivera | Logout

How do I mock this?

Asked 2011-08-11T18:03:17.750
13

In a .NET windows app, I have a class named EmployeeManager. On instantiation, this class loads employees into a List from the database that haven't completed registration. I'd like to use EmployeeManager in unit test. However, I don't want to involve the database.

From what I understand about this scenario, I need an IEmployeeManager interface, which is only used for testing purposes. This doesn't seem right since the interface has no other use. However, it will allow me to create some EmployeeManager test class that loads employees without involving the database. This way, I can assign values that would have otherwise come from the database.

Is the above correct and do I need to Mock it? Mocking (Moq framework) seems to use lots of code just to do simple things such as assigning a property. I don't get the point. Why mock when I can just create a simple test class from IEmployeeManager that will provide what I need?

Edit
Report

1 Answer

5

From what I understand about this scenario, I need an IEmployeeManager interface, which is only used for testing purposes. This doesn't seem right since the interface has no other use.

It's well worth creating the interface. Note also that the interface actually has multiple purposes:

  1. The interface identifies roles or responsibilities provided by an actor. In this case, the interface identifies the roles and responsibilities of the EmployeeManager. By using an interface you're preventing an accidental dependency on something database specific.
  2. The interface reduces coupling. Since your application won't depend on the EmployeeManager, you're free to swap out its implementation without needing to recompile the rest of the application. Of course, this depends on project structure, number of assemblies, etc., but it nevertheless allows this type of reuse.
  3. The interface promotes testability. When you use an interface it becomes much easier to generate dynamic proxies that allow your software to be more easily tested.
  4. The interface forces thought1. Ok, I kind of already alluded to it, but it's worth saying again. Just using an interface alone should make you think about an object's roles and responsibilities. An interface shouldn't be a kitchen sink. An interface represents a cohesive set of roles and responsibilities. If an interface's methods aren't cohesive or aren't almost always used together then it's likely that an object has multiple roles. Though not necessarily bad, it implies that multiple distinct interfaces are better. The larger an interface the harder it is to make it covariant or contravariant and, therefore, more malleable in code.

However, it will allow me to create some EmployeeManager test class that loads employees without involving the

answered 2011-08-11T19:42:08.647

Your Answer