I'm going to try TDD and I'm researching right tools for that. At work we are using MS Fakes so it would be fine not to change it and use MS Fakes with TDD. But I have one serious problem. It seems to me that MS Fakes are intended to use in scenario: write code -> write unit test for it. How can I mock some interface during TDD with MS Fakes?
For example I have following code in one file (refactoring will be done later)
[TestClass]
public class MyTests
{
[TestMethod]
public void ShouldReturnSomeResultIfEmptyCollectionOfCustomersWasReturned()
{
// arrange
ICustomerRepository customerRepository = null;
var targetService = new MyTargetService(customerRepository);
// act
int result = targetService.MyMethod();
// assert
Assert.AreEqual(1, result);
}
}
public class MyTargetService : IMyTargetService
{
private readonly ICustomerRepository customerRepository;
public MyTargetService(ICustomerRepository customerRepository)
{
this.customerRepository = customerRepository;
}
public int MyMethod()
{
if (customerRepository.GetCustomers().Any())
{
return 0;
}
return 1;
}
}
public interface IMyTargetService
{
}
public interface ICustomerRepository
{
Customer[] GetCustomers();
}
public class Customer
{
}
During my TDD process I've put everything in one file and then will refactor this and move to different assemblies. But I need to mock inline in this place ICustomerRepository customerRepository = null;
. I can do it easy with NSubstitute for example. But if I use MS Fakes I need first to move this interface to another project, reference this project from one where unit test is situated and press "Add Fake Assembly". This seems very complicated workflow which makes TDD not so quick and efficient.
I want to have code like this just in place without all those strange manipulations:
ICustomerRepository customerRepository = new StubBase<ICustomerRepository>
{
GetCustomers = () => Enumerable.Empty<Customer>().ToArray(),
};
But StubBase<>
is abstract. So is there any way to do such thing with MS Fakes or no?
Fakes relies on build-time code generation and currently requires you to define the interfaces/classes you want to stub in a separate project. Compared to other frameworks that generate stubs at run time, such as NSubstitute, this requires one additional refactoring step before you can compile a new test - moving the new interface you just created from the test project to the target project. This refactoring can be accomplished in just a few keystrokes with Resharper.