-
Notifications
You must be signed in to change notification settings - Fork 3
AutoMockBaseTest
The AutoMockBaseTest class inherits from Base Test With Sut class and provides the ability to create the Sut using a mock.
public abstract class AutoMockBaseTest<TSut, TContract>
: BaseTestWithSut<TContract> where TSut : class, TContract
{ ... }##Benefits The benefit is not only that we don't need to create the mock manually but also all the dependencies that are part of the Sut constructor will be created for us.
For example, without using the AutoMock feature we would have to write something like this for the MovieLibrary class:
protected override void BeforeCreateSut()
{
_criticMock = Mock<IMovieCritic>();
_movieFactoryMock = Mock<IMovieFactory>();
....
}
protected override MovieLibrary CreateSut()
{
return new MovieLibrary(_criticMock, _movieFactoryMock, _otherMockHere)
}So we create the concrete class and also we have to initialize a some point the dependencies that the class needs (i.e: critic, factory, etc).
Using auto mocking we don't need to add any code, because the implementation uses StructureMap automocker, doing:
protected override TContract CreateSut()
{
return this.AutoMocker.ClassUnderTest;
}The Sut property will be of type TContract because the class inherits using TContract as the generic type of the base class.
This choice reflects the idea that if you are using a base class or interface any change should be done first to that interface and then to the concrete class. Otherwise you will do the change to the concrete class and forget to put it in the interface.
Because of this idea and also because it may be useful having the concrete class available another method is declared to do so:
protected TSut ConcreteSut
{
get { return (TSut)this.Sut; }
}Because the dependencies are created for us the class provides a method to access them:
public T Dep<T>() where T : class
{
return this.AutoMocker.Get<T>();
}This works for all the dependencies for the Sut but also for any other dependency that you may like to use, just remember that only one instance can me mocked using the Dep method, if you need more than one you will have to create it on your own.
If you need to pass as a parameter a value type or u need to pass more than one instance of the same class you can always use the CreateSut method and override it, so the auto mocking won't do it for you. The good thing is that you use the dependencies from the auto mocker like this:
protected override TSUT CreateSut()
{
return new MovieLibrary(32, "Nice Library", Dep<IMovieCritic>(), Dep<IMovieFactory>());
}