Getting started with TDD and the repository pattern, I'm wondering if it makes any sense testing this...
Using the repository pattern, I have this interface:
public interface ICustomerRepository
{
IList<Customer> List();
Customer Get(int id);
}
I have like 50 different entities, so 50 different repository interfaces/implementations.
My question is if it's correct to test each repository, by mocking up the interface, like:
[TestMethod]
public void List_Should_Return_Two_Customers()
{
// Arrange
var customerr = new List<Customer>();
customer.Add(new Customer());
customer.Add(new Customer());
var repository = new Mock<ICustomerRepository>();
repository.Setup(r => r.List()).Returns(customer);
// Assert
Assert.AreEqual(2, repository.Object.List().Count);
}
[TestMethod]
public void Get_Should_Return_One_Customer()
{
// Arrange
var customer = new List<Customer>();
customerr.Add(new Customer() { Id = 1 });
customerr.Add(new Customer() { Id = 2 });
var repository = new Mock<ICustomerRepository>();
repository.Setup(r => r.Get(1)).Returns(customer.Where(w => w.Id == 1).First());
// Assert
Assert.IsTrue(repository.Object.Get(1).Id == 1);
}
Does it make any sense testing a fake implementation of these interfaces? To me it does not.
No, it does not make sense. Obviously you should test only implementations, not interfaces. There is nothing to test in an interface.
The only things being tested in your examples are the mocking framework, the .NET list and some LINQ extension methods. There is no need to test those, somebody else already takes care of that.
Maybe the intention was to provide unit tests for the fact that the interface exists and has certain methods? In that case, the tests are still unnecessary. This is implicitly tested by the tests for other code that relies on the interface declaration.
You should only create an ICustomerRepository mock when you need a fake implementation in order to test other code.
Yes, it is "correct" to test each Repository. Repositories exist to abstract your database away from the code, and should be verified that they are working correctly. Your data access layer is arguably one of the most important components to test.
The others are right.
You can't test interfaces.
You are in fact testing mocks, and that doesn't make sense.
Usually I test repositories against a database, so, not so much unit testing for them.
And for testing anything above them I mock them.
Keep in mind that 50 types of entities doesn't mean 50 repositories.
Regards.
Can I propose an alternate solution...
As Simple as your Repository is (if they are all the same methods except for what they return) why don't you make a base class using Generics. Then you would only have to test the base class.
public interface IRepository<TEntity> where TEntity : class
{
IList<TEntity> List();
TEntity Get(int id);
}
public abstract class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
IList<TEntity> List()
{
//DataContext.GetTable<TEntity>().ToList();
}
TEntity Get(int id)
{
//Might have to do some magic here... you can use reflection or create
//an abstract method that the derived class must override that returns
//a delegate id selector.
}
}
Related
I'm pretty new with using Moq and I'm running into an issue were one of my method calls is returning null despite the fact that I have mocked it.
I am mocking the following interfaces.
public interface IUnitOfWorkFactory
{
IUnitOfWork Create(KnownDbContexts knownDbContexts);
}
public interface IUnitOfWork : IDisposable
{
Task SaveChanges();
IRepository Repository { get; }
}
Then in my unit test code it looks like this.
_uowFactoryMock.Setup(x => x.Create(It.IsAny<KnownDbContexts>()))
.Returns(It.IsAny<IUnitOfWork>());
The code I'm testing looks like this.
using (var uow = _unitOfWorkFactory.Create(KnownDbContexts.UserDefined1))
{
// At this point 'uow' is null.
}
Why is IUnitOfWorkFactory.Create returning null?
In your current code, the method Create of the mocked factory returns an object of type It.IsAny<IUnitOfWork>.
However you want your mocked factory to return a mock of the unit of work, as such:
var uowMock = new Mock<IUnitOfWork>();
// here mock uowMock's methods (ie SaveChanges) in the same way it is done below for the factory
_uowFactoryMock.Setup(x => x.Create(It.IsAny<KnownDbContexts>()))
.Returns(uowMock.Object);
I'm working on a quite large application. The domain has about 20-30 types, implemented as ORM classes (for example EF Code First or XPO, doesn't matter for the question). I've read several articles and suggestions about a generic implementation of the repository pattern and combining it with the unit of work pattern, resulting a code something like this:
public interface IRepository<T> {
IQueryable<T> AsQueryable();
IEnumerable<T> GetAll(Expression<Func<T, bool>> filter);
T GetByID(int id);
T Create();
void Save(T);
void Delete(T);
}
public interface IMyUnitOfWork : IDisposable {
void CommitChanges();
void DropChanges();
IRepository<Product> Products { get; }
IRepository<Customer> Customers { get; }
}
Is this pattern suitable for really large applications? Every example has about 2, maximum 3 repositories in the unit of work. As far as I understood the pattern, at the end of the day the number of repository references (lazy initialized in the implementation) equal (or nearly equal) to the number of domain entity classes, so that one can use the unit of work for complex business logic implementation. So for example let's extend the above code like this:
public interface IMyUnitOfWork : IDisposable {
...
IRepository<Customer> Customers { get; }
IRepository<Product> Products { get; }
IRepository<Orders> Orders { get; }
IRepository<ProductCategory> ProductCategories { get; }
IRepository<Tag> Tags { get; }
IRepository<CustomerStatistics> CustomerStatistics { get; }
IRepository<User> Users { get; }
IRepository<UserGroup> UserGroups { get; }
IRepository<Event> Events { get; }
...
}
How many repositories cab be referenced until one thinks about code smell? Or is it totally normal for this pattern? I could probably separate this interface into 2 or 3 different interfaces all implementing IUnitOfWork, but then the usage would be less comfortable.
UPDATE
I've checked a basically nice solution here recommended by #qujck. My problem with the dynamic repository registration and "dictionary based" approach is that I would like to enjoy the direct references to my repositories, because some of the repositories will have special behaviour. So when I write my business code I would like to be able to use it like this for example:
using (var uow = new MyUnitOfWork()) {
var allowedUsers = uow.Users.GetUsersInRolw("myRole");
// ... or
var clothes = uow.Products.GetInCategories("scarf", "hat", "trousers");
}
So here I'm benefiting that I have a strongly typed IRepository and IRepository reference, hence I can use the special methods (implemented as extension methods or by inheriting from the base interface). If I use a dynamic repository registration and retrieval method, I think I'm gonna loose this, or at least have to do some ugly castings all the time.
For the matter of DI, I would try to inject a repository factory to my real unit of work, so it can lazily instantiate the repositories.
Building on my comments above and on top of the answer here.
With a slightly modified unit of work abstraction
public interface IMyUnitOfWork
{
void CommitChanges();
void DropChanges();
IRepository<T> Repository<T>();
}
You can expose named repositories and specific repository methods with extension methods
public static class MyRepositories
{
public static IRepository<User> Users(this IMyUnitOfWork uow)
{
return uow.Repository<User>();
}
public static IRepository<Product> Products(this IMyUnitOfWork uow)
{
return uow.Repository<Product>();
}
public static IEnumerable<User> GetUsersInRole(
this IRepository<User> users, string role)
{
return users.AsQueryable().Where(x => true).ToList();
}
public static IEnumerable<Product> GetInCategories(
this IRepository<Product> products, params string[] categories)
{
return products.AsQueryable().Where(x => true).ToList();
}
}
That provide access the data as required
using(var uow = new MyUnitOfWork())
{
var allowedUsers = uow.Users().GetUsersInRole("myRole");
var result = uow.Products().GetInCategories("scarf", "hat", "trousers");
}
The way I tend to approach this is to move the type constraint from the repository class to the methods inside it. That means that instead of this:
public interface IMyUnitOfWork : IDisposable
{
IRepository<Customer> Customers { get; }
IRepository<Product> Products { get; }
IRepository<Orders> Orders { get; }
...
}
I have something like this:
public interface IMyUnitOfWork : IDisposable
{
Get<T>(/* some kind of filter expression in T */);
Add<T>(T);
Update<T>(T);
Delete<T>(/* some kind of filter expression in T */);
...
}
The main benefit of this is that you only need one data access object on your unit of work. The downside is that you don't have type-specific methods like Products.GetInCategories() any more. This can be problematic, so my solution to this is usually one of two things.
Separation of concerns
First, you can rethink where the separation between "data access" and "business logic" lies, so that you have a logic-layer class ProductService that has a method GetInCategory() that can do this:
using (var uow = new MyUnitOfWork())
{
var productsInCategory = GetAll<Product>(p => ["scarf", "hat", "trousers"].Contains(u.Category));
}
Your data access and business logic code is still separate.
Encapsulation of queries
Alternatively, you can implement a specification pattern, so you can have a namespace MyProject.Specifications in which there is a base class Specification<T> that has a filter expression somewhere internally, so that you can pass it to the unit of work object and that UoW can use the filter expression. This lets you have derived specifications, which you can pass around, and now you can write this:
using (var uow = new MyUnitOfWork())
{
var searchCategories = new Specifications.Products.GetInCategories("scarf", "hat", "trousers");
var productsInCategories = GetAll<Product>(searchCategories);
}
If you want a central place to keep commonly-used logic like "get user by role" or "get products in category", then instead of keeping it in your repository (which should be pure data access, strictly speaking) then you could have those extension methods on the objects themselves instead. For example, Product could have a method or an extension method InCategory(string) that returns a Specification<Product> or even just a filter such as Expression<Func<Product, bool>>, allowing you to write the query like this:
using (var uow = new MyUnitOfWork())
{
var productsInCategory = GetAll(Product.InCategories("scarf", "hat", "trousers");
}
(Note that this is still a generic method, but type inference will take care of it for you.)
This keeps all the query logic on the object being queried (or on an extensions class for that object), which still keeps your data and logic code nicely separated by class and by file, whilst allowing you to share it as you have been sharing your IRepository<T> extensions previously.
Example
To give a more specific example, I'm using this pattern with EF. I didn't bother with specifications; I just have service classes in the logic layer that use a single unit of work for each logical operation ("add a new user", "get a category of products", "save changes to a product" etc). The core of it looks like this (implementations omitted for brevity and because they're pretty trivial):
public class EFUnitOfWork: IUnitOfWork
{
private DbContext _db;
public EntityFrameworkSourceAdapter(DbContext context) {...}
public void Add<T>(T item) where T : class, new() {...}
public void AddAll<T>(IEnumerable<T> items) where T : class, new() {...}
public T Get<T>(Expression<Func<T, bool>> filter) where T : class, new() {...}
public IQueryable<T> GetAll<T>(Expression<Func<T, bool>> filter = null) where T : class, new() {...}
public void Update<T>(T item) where T : class, new() {...}
public void Remove<T>(Expression<Func<T, bool>> filter) where T : class, new() {...}
public void Commit() {...}
public void Dispose() {...}
}
Most of those methods use _db.Set<T>() to get the relevant DbSet, and then just query it with LINQ using the provided Expression<Func<T, bool>>.
I have a large legacy WPF project that I'm now trying to get unit tested with NUnit (v. 2.6.3) and Moq (v. 4.2), but I'm having trouble with mocking certain classes. There's one in particular, a control class derived from System.Windows.Forms.Integration.WindowsFormsHost, that's needed all over the project and has a lot of external dependencies, so it's very important to be able to mock it.
Let's call that class Foo, and here's the test case:
[TestFixture,RequiresSTA]
public class TestMainWindowViewModel {
[Test]
public void Test1() {
var mockRepository = new MockRepository(MockBehavior.Loose) { DefaultValue = DefaultValue.Empty };
var mockFoo = mockRepository.Create<Foo>();
var sut = new MainWindowViewModel(mockFoo.Object);
}
}
My problem is that for some weird reason, while evaluating parameter mockFoo.Object in the last line, we go straight inside the constructor of the concrete class Foo! I have confirmed that this really happens with debugger, and also, the test run crashes with an error of not finding the DLL's the concrete implementation depends on.
Any ideas what could be causing this? As far as I understand, there should be NO connection to the concrete implementation here!
Thanks in advance for any advice!
-Seppo
Any ideas what could be causing this? As far as I understand, there should be NO connection to the concrete implementation here!
Moq creates its objects (mocks) by deriving from concrete implementation (your case) or implementing interface (typical, more common case):
// implement interface
var mock1 = new Mock<IService>();
// derive from ServiceImplementation
var mock2 = new Mock<ServiceImplementation>();
This is how underlying mechanisms work -- in order to create mock, Moq will have to dynamically create new type representing that mock, either by implementing interface or deriving from base class. Which means your Foo constructor should and is executed. This is how it works.
Since this is legacy code class (Foo) I suggest wrapping it with new, mockable interface and make your code depend on this interface instead:
interface IFoo
{
void DoFoo();
}
class FooWrapper : IFoo
{
private readonly Foo legacyFoo;
public FooWrapper(Foo legacyFoo)
{
this.legacyFoo = legacyFoo;
}
public void DoFoo()
{
legacyFoo.DoFoo();
}
}
Your new (non-legacy) code should depend on IFoo, not Foo and you'll be good to go.
I am new to the whole MOQ movement... which by the way is pretty cool ... and I am mocking all kinds of stuff now..
Anyway, I ran into this scenario and was wondering how to go about mocking it up.
I have an class that implements the interface that I want to mock:
public interface ImyInterface
{
void doit();
}
public abstract class myBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class
{
protected TChannel Channel { get; private set; }
// ICommunicationObject implementation not shown
}
public class myIIntClass : myBase<ImyInterface>, ImyInterface
{
public myIIntClass()
{
}
public void doit()
{
Channel.doit();
}
}
I think my moq test doesn't mock anything... but I am unsure and hoping to get some insight on how to either write it correctly or refactor my class:
Here is my current MOQ test:
MyClass myClass = null;
Mock<ImyInterface> moq = new Mock<ImyInterface>();
moq.Setup(x => x.doit());
myClass = (MyClass)moq.Object;
myClass.doit();
moq.VerifyAll();
Thanks from one moqer to another... :-)
I feel like maybe you're missing the point of mocking here. You mock dependencies that exist in a unit of work you're testing. So, let's say I'm testing doit here in the concrete implementation of MyClass; I want to make sure it works right. Now, let's say that method has a dependency to another class; it calls a method on it that returns a boolean value. What I want to do is mock that class because I want to make sure that MyClass.doit behaves right when it returns true and when it returns false.
See, in the example above, what I've done is ensured that no other dependencies are affecting the code flow of MyClass.doit; I'm forcing MyClass.doit down a very specific path; I want to test that path.
The code you've created literally performs nothing because it just executes the mocked up method.
You don't mock/stub the unit under test. If you are testing the doIt(), you don't mock that, you mock its (or class) dependencies.
I am unit testing an ICustomerRepository interface used for retrieving objects of type Customer.
As a unit test what value am I gaining by testing the ICustomerRepository in this manner?
Under what conditions would the below test fail?
For tests of this nature is it advisable to do tests that I know should fail? i.e. look for id 4 when I know I've only placed 5 in the repository
I am probably missing something obvious but it seems the integration tests of the class that implements ICustomerRepository will be of more value.
[TestClass]
public class CustomerTests : TestClassBase
{
private Customer SetUpCustomerForRepository()
{
return new Customer()
{
CustId = 5,
DifId = "55",
CustLookupName = "The Dude",
LoginList = new[]
{
new Login { LoginCustId = 5, LoginName = "tdude" },
new Login { LoginCustId = 5, LoginName = "tdude2" }
}
};
}
[TestMethod]
public void CanGetCustomerById()
{
// arrange
var customer = SetUpCustomerForRepository();
var repository = Stub<ICustomerRepository>();
// act
repository.Stub(rep => rep.GetById(5)).Return(customer);
// assert
Assert.AreEqual(customer, repository.GetById(5));
}
}
Test Base Class
public class TestClassBase
{
protected T Stub<T>() where T : class
{
return MockRepository.GenerateStub<T>();
}
}
ICustomerRepository and IRepository
public interface ICustomerRepository : IRepository<Customer>
{
IList<Customer> FindCustomers(string q);
Customer GetCustomerByDifID(string difId);
Customer GetCustomerByLogin(string loginName);
}
public interface IRepository<T>
{
void Save(T entity);
void Save(List<T> entity);
bool Save(T entity, out string message);
void Delete(T entity);
T GetById(int id);
ICollection<T> FindAll();
}
I may be missing something but it seems like every single aspect of your test is mocked up?
Generally speaking you only mock up the objects that aren't core to the test. In this case you may use this repository as the source for a function which you expect to do something with the repository to retrieve customer #5 and perform an operation on it.
For example you may mock up a customer repository so that you can call a method that verifies the login of a user. You'd use your mock repository to prevent your unit-test from relying on a real data-source, not to test your mock repository.
Rule #1 of testing:
Know what the purpose of your test is and what it is trying to prove before you write it. If you don't know what it proves, then it's useless :)
As the other posters have correctly said, you're stubbing an interface and then calling the stub -- this doesn't prove anything about whether your production code works.
What is a stub?
Stubs are used to provide canned values to drive some aspect of the class under test. E.g. Say you have a CustomerService that has an instance of type ICustomerRepository. If you wanted to see that the CustomerService could gracefully handle an error case when the repository was empty, you would stub the ICustomerRepository's GetCustomerById method to return nothing/null/throw an exception, then ensure that the CustomerService method did the correct thing (e.g. return a customer not found result).
I.e. the stub is just a collaborator that helps you reach the particular condition/behaviour of interest. We're testing CustomerService and the stubbed ICustomerRepository merely helps us achieve our goal.
You're not the first to ask this very question :). I usually advise developers to hand-roll their test doubles at first. It helps to understand all of the interactions and what the framework is actually doing for you.
Interfaces, by definition, are just contracts, so there's no code to test. You want to write unit tests against the concrete implementation(s) of the interface, because that is where the actual execution code lives.
If there's no concrete implementation of the interface and you're just mocking a concrete implementation, then your unit test is just based on a mock. That isn't really of much value.
Your test makes no sense to me. You are testing if a preprogrammed stub is returning the values you feed it, You are not testing any real code.
Follow dcp's reply. An interface is a declaration of methods. You should test implementations of these.