what is a good mocking framework to start mocking with in asp.net MVC? (novice and probably not a hardcore mocker)
i want to use mocking in my unit tests.
Till now i more programmed 'tests' and not 'unittests' because i tested whole program flows, but reading discussions i can see the beauty of a mock object, from time to time.
But, looking around, there are a lot of frameworks available, and i want to make sure i start with a good one, because i'd like to invest tim开发者_开发百科e in learning a mock framework only once.
So as i said in the title, i'm a novice for mocking, using asp.net mvc, and don't think i'll be a hardcore mocker, investigating the edges of a mocking framework.
To give you an idea of what i like in the IOC frameworks i like unity and structuremap.
Michel
I would recommend Moq. I previously tried Rhino, but I personally find the Moq API to be slicker.
I have used both Rhino Mocks and Moq as part of ASP.NET MVC projects with great success. While in the past these frameworks differed quite a bit, their feature sets have converged over the years and so either one would be a good choice.
Since you're specifically targeting MVC, you should consider what Phil Haack has to say as well.
I recommend Moq.
Say you have a class MyClass
defined as follows:
public class MyClass{
private IMyDependency dependency;
public MyClass(IMyDependency dependency){
this.dependency = dependency;
}
public void DoSomething(){
//invoke a method on the dependency
this.dependency.DoWork();
}
}
IMyDependency
is declared like this:
public interface IMyDependency{
void DoWork();
}
Now using Moq, you could test that the dependency is called like so:
public void DoSomethingWillInvokeDoWorkCorrectly()
{
var mock = new Mock<IMyDependency>();
mock.Setup(imd => imd.DoWork()).Verifiable();
var sut = new MyClass(mock.Object);
sut.DoSomething();
//Verify that the mock was called correctly
mock.Verify();
}
Now that was a very simple example, so lets spice it up a little.
public class MyClass2{
private IMyDependency2 dependency;
public MyClass2(IMyDependency2 dependency){
this.dependency = dependency;
}
public void DoSomething(int i){
//invoke a method on the dependency
this.dependency.DoWork(i * 2);
}
}
IMyDependency2
is declared like this:
public interface IMyDependency2{
void DoWork(int i);
}
A test method that tests that the correct parameter is passed to the dependency could look like this:
public void DoSomethingV2WillInvokeDoWorkCorrectly()
{
var mock = new Mock<IMyDependency2>();
int parameter = 60;
mock.Setup(imd => imd.DoWork(It.Is<int>(i => i == 2 * parameter)).Verifiable();
var sut = new MyClass2(mock.Object);
sut.DoSomething(parameter);
//Verify that the mock was called correctly
mock.Verify();
}
As you can see, the Setup
method now adds a constraint on the parameter passed to DoWork
, saying that it is an int the value of which must be twice the value of the parameter
variable.
精彩评论