I want to test a function with the type signature
public static void DoSomething<T>(T something)
where T : class, IInterfaceA, IInterfaceB, new()
which uses new T() internally.
I'm having problems creating a mock for T. Thanks to another question, I already found a solution for mocking multiple interfaces. However, I'm unable to create a mock satisfying the new() constraint. How do I solve this using Moq?
You have two options:
Use unconstraint mocking framework. In .NET it means either Isolator or JustMock. Both use IL weaving to inject code during runtime and can fake/mock object which are created inside the production code.
Split DoSomething logic and use dependency injection instead of creating the object as part of the logic.
Choosing between the two depends on how hard it is to split the logic, whether the remaining code has enough "meat" in it and if you're willing to pay for a Mocking framework that can fake new
Related
I'm relatively new to unit testing, and very new to C#, but I've been trying to test code that uses static classes with static methods, and it seems like I have to write huge amounts of boilerplate code in order to test, and that code would then also probably need to be tested.
For example: I'm using the System.Web.Security.Membership class, with a method ValidateUser on it. It seems like I need to create an interface IMembership containing the method ValidateUser, then create a class MembershipWrapper that implements IMembership, implementing the method ValidateUser and passing the arguments on to the actual Membership class. Then I need to have properties on my class that uses the Membership to reference the wrapper so that I can inject the dependency for a mock object during testing.
So to test 1 line of code that uses Membership, I've had to create an interface, and a class, and add a property and constructor code to my class. This seems wrong, so I must be getting something wrong. How should I be going about this testing? I've had a brief look at some frameworks/libraries that do dependency injection, but they still appear to require lots of boilerplate, or a very deep understanding of what's going on under the hood.
I don't see anything wrong in making your system loosely coupled. I believe you don't complain on creating constructor parameters and passing abstract dependencies to your classes. But instantiating dependencies in place looks so much easier, does it?
Also, as I pointed in comments, you can reuse wrappers later. So, that is not such useless work, as it seems from first glance.
You are on the right way, and think you are not testing single line of code, in this case you are writing important test to ensure that your code interacts with membership provider in the right way, this is not simple unit test rather "mock-based" integration test. I think it worth creating all these mocks and have covered by tests this part of application.
And yes, it seems overkill but no other way - either you use some helpers/libraries either wrap third-party static dependencies yourself.
I you're not happy taking the approach of constructor injection, you could look at using Ambient Context
You basically set up a default which will call System.Web.Security.Membership.ValidateUser
You then call the exposed method on the context in your code and you can now mock it for your tests
This allows you to write less setup code, but it also hides the fact that you have a dependency, which might be a problem in the future (depending on how you're reusing code)
If you're using VS2012, you can always use Shims in Microsoft Fakes for static calls (or .Net library calls too).
http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/hh549176.aspx
I have some classes(call it Class A) which I would like to unit test but it uses some classes(call it Class B) with some static methods.
To remove reference to these classes with static methods I have to refactor them to be instance methods and inject into Class A.
Issue is Class A has lots of services(Not only class B) its seems to depend on?
What is the best option in this scenario? Have a constructor that has a lot of parameters that can take in these services?
Or is there something wrong with my design the fact that class A has so many dependencies?
Thanks
Issue is Class A has lots of services(Not only class B) its seems to depend on?
Several dependencies are usually indicating a code smell. Your class is most likely breaking Single Responsibility Principle.
Try to break down the class into smaller classes.
Unit tests are a good quality indicator. Classes that are hard to test are often violating one or more of the SOLID principles.
What is the best option in this scenario? Have a constructor that has
a lot of parameters that can take in these services?
Constructor injection is always the preferred way since it's easy to tell what dependencies a class has.
I would recommend constructor injection, especially if you have a lot of dependencies to inject, only if you're using a Dependency Injection framework like Unity or Ninject. Refactoring an existing code-base to add constructor injection everywhere is usually messy, and probably requires storing all the services in local variables in many base classes just so you can pass them on to classes further down the chain.
What I would do in this case is use some implementation of the ServiceLocator pattern, with a single static ServiceLocator/Container class that you can use to access your non-static services:
IService _service = ServiceLocator.GetService<IService>();
This will require the minimum amount of refactoring in existing code (just replace MyService.DoSomething() with _service.DoSomething(), and still allow you to mock and test your code by replacing the ServiceLocator's internet collection:
ServiceLocator.Register<IService>(myFakeService);
I've seen examples of this where an interface is provided to a factory and it generates objects that implement the interface. This isn't that complicated to me, but what I don't get is how that can be used to implement behavior.
Take for example the ChannelFactory in WCF... when you generate a channel from an interface it exposes methods (from the interface) that when invoked call remote procedures. I seem to have a small gap in my knowledge on how this can be done. It's probably a common design pattern but I figured I'd use SO as a research extension once again.
Usually happens through code emission. See the classes in System.Reflection.Emit.
For example, you could get an interface Type and go over the methods it declares, then build your own type which inherits it, using TypeBuilder, and implement whatever functionality you desire in the methods (or just them make empty / do a return default(T)), using MethodBuilder, and so on, until you've satisfied the interface.
Mocking frameworks that mock an interface generate a dynamic class that implements the interface. The behavior of the mocked method(s) will depend on the framework. Generally, the method will do nothing unless an implementation is provided through the mock.
For example:
Mock<IRepository> repMock = new Mock<IRepository>();
repMock.Setup(r => r.FindById(1)).Returns(new MyObject());
Assuming the IRepository interface defines a FindByID method, the Setup method of the mock dynamically generates an implementation of the method and "injects" it into the mock. This is done using Reflection.Emit, which can be used to dynamically build IL instructions and compile them on the fly.
I have occasionally heard or read about people asserting their interfaces in a unit test. I don't mean mocking an interface for use in another type's test, but specifically creating a test to accompany the interface.
Consider this ultra-lame and off-the-cuff example:
public interface IDoSomething
{
string DoSomething();
}
and the test:
[TestFixture]
public class IDoSomethingTests
{
[Test]
public void DoSomething_Should_Return_Value()
{
var mock = new Mock<IDoSomething>();
var actualValue = mock.Expect(m => m.DoSomething()).Returns("value");
mock.Object.DoSomething();
mock.Verify(m => DoSomething());
Assert.AreEqual("value", actualValue);
}
}
I suppose the idea is to use the test to drive the design of the interface and also to provide guidance for implementors on what's expected so they can draw good tests of their own.
Is this a common (recommended) practice?
In my opinion, just testing the interface using a mocking framework tests little else than the mocking framework itself. Nothing I would spend time on, personally.
I would say that what should drive the design of the interface is what functionality that is needed. I think it would be hard to identify that using only a mocking framework. By creating a concrete implementation of the interface, what is needed or not will become more obvious.
The way I tend to do it (which I by no means claim is the recommended way, just my way), is to write unit tests on concrete types, and introduce interfaces where needed for dependency injection purposes.
For instance, if the concrete type under test needs access to some data layer, I will create an interface for this data layer, create a mock implementation for the interface (or use a mocking framework), inject the mock implementation and run the tests. In this case the interface serves no purpose than offering an abstraction for the data layer.
I've never seen anything like this but it seems pointless. You would want to test the implementation of these interfaces, not the interfaces themselves.
Interfaces are about well designed contracts, not well-implemented ones. Since C# is not a dynamic language that would allow the interface to go un-implemented at runtime, this sort of test is not appropriate for the language. If it were Ruby or Perl, then maybe...
A contract is an idea. The soundness of an idea is something that requires the scrutiny of a human being at design time, not runtime or test time.
An implementation can be a "functional" set of empty stubs. That would still pass the "Interface" test, but would be a poor implementation of the contract. It still doesn't mean the contract is bad.
About all a specific Interface test accomplishes is a reminder of original intention which simply requires you to change code in 2 places when your intentions change.
This is good practice if there are testable black box level requirements that implementers of your interface could reasonably be expected to pass. In such a case, you could create a test class specific to the interface, that would be used to test implementations of that interface.
public interface ArrayMangler
{
void SetArray (Array myArray);
Array GetSortedArray ();
Array GetReverseSortedArray();
}
You could write generic tests for ArrayMangler, and verify that arrays returned by GetSortedArray are indeed sorted, and GetReverseSortedArray are indeed sorted in reverse.
The tests could then be included when testing classes implementing ArrayMangler to verify the reasonably expected semantics are being met.
In my opinion is not the way to go. A interface is created as an act of refactoring (extract interface) not TDD. So you start by creating a class with TDD and after that you extract an interface (if needed).
The compiler itself does the verification of the interface. TDD does the validation of the interface.
You may want to check out code contracts in c# 4 as you are slightly bordering into that area in how you phrase the question. You seem to have bundled a few concepts together, and you are understandably confused.
The short answer to your question is that you've probably misheard/misunderstood it. TDD will drive the evolution of the Interface.
TDD tests the interface by verifying that coverage is achieved without involving the concrete types (the specific ones that implement the interface).
I hope this helps.
Interfaces are about relationships between objects, which means you can't "test-drive" an interface without knowing the context it's being called from. I use interface discovery when using TDD on the object that calls the interface, because the object needs a service from its environment. I don't buy that interfaces can only be extracted from classes, but that's another (and longer) discussion.
If you don't mind the commercial, there's more in our book at http://www.growing-object-oriented-software.com/
I am using Rhino mocks for unit test mocking of objects. Our DAL uses codesmith to generate code from .netTiers templates, which creates these DataRepository classes that contain all the methods for CRUD type transaction to the datasource. In unit testing, I am trying to mock this data repository object which has no interface class to use as a stub.
In Brief, has anyone successfully used Rhino mocks to mock a .netTiers generated DataRepository, avoiding the need for a test database and real transactions against the datasource that needs to be tore down at the end??
I've been pondering this one for a while, as no one has stepped up and written a mock DataRepository implementation for netTiers yet (to my knowledge).
As I don't care too much for the record-replay steps of TypeMock and RhinoMocks, I've opted for the newer Moq, which will happily mock either the DataRepository classes or the Service layer calls themselves with minimal hassle.
Assuming you're on .NET 3.5, I'd recommend it.
In short, Rhino can only mock types that are either interfaces or non-sealed classes. And then, you can only stub methods that are virtual or abstract.
If your goal is to substitute a DataRepository with a mock implementation I think you will have to look into more advanced mocking frameworks like TypeMock.
If you're in control of the CS templates, another option would be to use the templates to also generate mock DataRepository implementations.