Unit Testing With Moq and Repository Pattern - c#

I am new to unit testing and I would like some help. I am using code first with repository pattern. I have a generic repository which contains generic CRUD operation called Generic Repository ( see blow )
public abstract class GenericRepository<T> where T : class
{
private HolidayDatabaseContext _dataContext;
private readonly IDbSet<T> _dbset;
protected GenericRepository(IDbFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
_dbset = DataContext.Set<T>();
}
protected IDbFactory DatabaseFactory
{
get;
private set;
}
protected HolidayDatabaseContext DataContext
{
get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
_dbset.Add(entity);
}
public virtual void Update(T entity)
{
_dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
_dbset.Remove(entity);
}
public virtual IEnumerable<T> Enumerable()
{
return _dbset.AsEnumerable<T>();
}
public virtual IQueryable<T> List()
{
return _dbset.AsQueryable<T>();
}
public virtual T GetSingleById(int id)
{
return _dbset.Find(id);
}
public void Save()
{
_dataContext.SaveChanges();
}
}
I have then inherited it into a User Repository and created some specific methods. see below
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(IDbFactory databaseFactory)
: base(databaseFactory) { }
public int HolidayEntitlement(int userId)
{
return HolidayEntitlement(userId, DateTime.Now);
}
public int HolidayEntitlement(int userId, DateTime dateTime)
{
//Get the User
var user = this.GetSingleById(userId);
//Work Total Entitlement
int entitlement = user.BaseHolidayEntitlement;
//Years in Service
entitlement += (dateTime - user.EmploymentStartDate).Days / 365;
return entitlement;
}
public int RemainingHolidayEntitlement(int userId)
{
return RemainingHolidayEntitlement(userId, DateTime.Now);
}
public int RemainingHolidayEntitlement(int userId, DateTime dateTime)
{
return int.MinValue;
}
}
I would like to Unit test HolidayEntitlement(int userId, DateTime dateTime) but i need to mock the GetSingleById part in the method
I have written this as a Test but it doesn't compile.
[TestMethod]
public void GetHolidayEntitlement25()
{
//How to write this Unit test
//Setup
var user = new User { AnnualHolidayIncrement = 1, BaseHolidayEntitlement = 25, EmploymentStartDate = new DateTime(2013, 1, 1),Id=1 };
Mock<UserRepository> mock = new Mock<UserRepository>();
mock.Setup(m => m.GetSingleById(1)).Returns(user);
Assert.AreEqual(25, mock.Object.HolidayEntitlement(1));
}
Any help would be appreciated

You seem to be saying that you only want to mock part of the interface. When you start encountering this sort of situation it suggests that you are mixing your concerns and probably doing something wrong somewhere.
In this instance your Repository is doing MUCH more than just CRUD and therefore has multiple responsibilities (it should only have one, lookup SOLID programming). You are performing Business logic in the repository and it should not live there! Anything other than simple CRUD operations should be moved out into the Business Logic Layer. I.e. your HolidayEntitlement method calculates something by applying some logic and is therefore NOT a CRUD / repository operation!
So... What you should do is move the business logic bits out into a new class, say UserLogic. Within the UserLogic class you would use an injected IUserRepository to communicate with your repository. In UserLogic that is where you would put your HolidayEntitlement method and it would make a call to IUserRepository.GetSingleById. So, when you then test your UserLogic class you would inject in your mock IUserRepository that would have the stub version of GetSingleById and then you will be back on the right track!
I hope that makes sense / helps?!
--ORIGINAL POST--
P.S. My original post stated that you should mock interfaces, not instances so this still applies and I will leave here for reference:
You should be mocking IUserRepository NOT UserRepository.
That is because UserRepository is an implementation of IUserRepository. You want to say that you are giving it a NEW implementation, i.e. your mock. At the moment you are using the ACTUAL class UserRepository.

Mocking is generally used when you need to supply a fake dependency and in this case you appear to be trying to Mock the System Under Test (SUT) which doesn't really make sense - there's literally no point because your test is not actually telling you anything about the behaviour of UserRepository; all you are doing is testing if you setup your Mock correctly which isn't very useful!
The test code you have given seems to indicate that you want to test UserRepository.HolidayEntitlement.
I would be much more inclined to move functions like that out of your Repository class and into a separate business-logic type class. This way you can test the logic of calculating a user's holiday entitlement in total isolation which is a major principle of unit testing.
In order to test that this function does what it's supposed to do (i.e perform a calculation based on properties of a User) you need to ensure that whatever User instance is being operated on within that function is 100% isolated and under your control - either with a Mock or Fake (Stub) instance of User, in this case Mocks are an excellent choice because you only need to implement the parts of the dependency that your SUT is going to need.
So, what you could do is this:
Define an interface for User
public interface IUser
{
int BaseHolidayEntitlement{get;set;}
DateTime EmploymentStartDate {get;set;}
//other properties for a User here
}
Implement this on your User class
public class User:IUser
{
//implemement your properties here
public int BaseHolidayEntitlement{get;set;}
public DateTime EmploymentStartDate {get;set;}
//and so on
}
Create a class for User logic
public class UserRules
{
public int GetHolidayEntitlement(IUser user,DateTime dateTime)
{
//perform your logic here and return the result
}
}
Now your test becomes much simpler and doesn't even need the repository
[TestMethod]
public void GetHolidayEntitlement_WithBase25_Returns25()
{
//Arrange
var user = new Mock<IUser>();
//setup known, controlled property values on the mock:
user.SetupGet(u=>u.BaseHolidayEntitlement).Returns(25);
user.SetupGet(u=>u.EmploymentStartDate).Returns(new DateTime(2013,1,1));
var sut = new UserRules();
int expected = 25;
//Act
int actual = sut.GetHolidayEntitlement(user.Object,DateTime.UtcNow);
//Assert
Assert.AreEqual(expected,actual,"GetHolidayEntitlement isn't working right...");
}

Related

How to deal with an IDisposable repository with Unity?

I have a job in which I have an IDisposable DbContext. I would like to unit test this job without hitting in a database. What options do i have to do this?
Im using the default Fakes assembly' of microsoft.
My job:
public void Work()
{
do
{
//code here
using (var repository = new Repository<User>())
{
repository.Save(user);
}
} while (true);
}
I'm trying to test and in this part of the test it fails because it actually creates a new instance of the Repository class.
My test Method:
using (ShimsContext.Create())
{
Data.Repository.Fakes.ShimRepository<Domain.Fakes.ShimUser>.Constructor = (a) => { };
Data.Repository.Fakes.ShimRepository<Domain.Fakes.ShimUser>.AllInstances.SaveT0 = (a, b) =>
{
};
var service = GetService();
service.Work(); //Throws exception
}
How can I fake this Save method?
You've violated DIP here, making unit testing your service far more difficult than it should be. You should also avoid generic repositories and favour role interfaces.
Instead, inject an abstraction into your service of your repository, e.g. IUsersRepository which defines your Save method. Then in your unit test of the service you can simply use a stub implementation of IUsersRepository.
Fakes tend to reveal that your code is not properly following the D in SOLID since you are creating dependencies inside your class instead of passing them in.
A much better pattern would to create an ISaveRepository interface that in turn implements IDisposable with an exposed Save() method. You should then inject an instance of your repository into your class. This will allow you to satisfy the using statement testing, as well as implement a mock that defines a .Save() method that does not hit the database.
public class Test
{
private readonly ISaveRepository _userRepository;
public Test(ISaveRepository userRepository)
{
_userRepository = userRepository;
}
public void Work()
{
using (_userRepository)
{
var cont = true;
do
{
_userRepository.Save(new User());
cont = false;
} while (cont);
}
}
}
public interface ISaveRepository : IDisposable
{
void Save<T>(T model);
}
public class Repository<T> : ISaveRepository
{
public void Dispose() { }
public void Save<TT>(TT model) {}
}
public class User {}

Unit Test In N Tier Architecture

I want to write tests for a program that is coded by someone else. But I have some problems while writing tests. I can't understand exactly how to fake some objects. I searched and found Unit Test for n tier architecture but It doesn't help me. For example, I want to write a test for code below (I know It is a dummy code for just clarification)
public List<CustomerObject> FetchCustomersByName(CustomerObject obj)
{
DAL customerDal = new DAL();
//Maybe other operations
List<CustomerObject> list = customerDal.FetchByName(obj.Name);
//Maybe other operations over list
return list;
}
I just want to test FetchCustomersByName but there is connection with DAL. I think creating stub class but In this case I have to change my original code. And it was coded by someone else. How can I write a test for this method?
Thanks in advance.
Don't unit test the data access layer. Write integration tests for it.
Mocking the dependencies in the DAL isn't just worth the trouble as it doesn't guarantee anything.
If you think about it, the DAL have dependencies on the SQL dialect and the database schema. Therefore your unit tests might work just fine. But when you run the real solution it can still fail. The reason can be that your SQL queries are incorrect or that the one of the class property types doesn't match the table column types.
unit tests are typically written for business logic. One thing that they catch is errors that doesn't generate exceptions such as incorrect conditions or calculation errors.
Update
Ok. So your example actually contains business logic. The method name fooled me.
You have to change the way you create your DAL classes. But you don't have to use constructor injection like Jack Hughes suggests. Instead you can use the factory pattern:
public List<CustomerObject> FetchCustomersByName(CustomerObject obj)
{
var customerDal = DalFactory.Create<CustomerDal>();
//Maybe other operations
List<CustomerObject> list = customerDal.FetchByName(obj.Name);
//Maybe other operations over list
return list;
}
That's bit easier since now you can just use "replace all" to change all var customerDal = new CustomerDal() to var customerDal = DalFactory.Create<CustomerDal>();
In that factory class you can call different implementations
public class DalFactory
{
public static IDalFactory Factory { get set; }
static DalFactory()
{
Factory = new DefaultDalFactory();
}
public static T Create<T>() where T : class
{
return Factory.Create<T>();
}
}
public interface IDalFactory
{
T Create<T>() where T : class
}
public class DefaultDalFactory : IDalFactory
{
public T Create<T>() where T : class
{
return new T();
}
}
The code isn't beautiful, but it solves your case with minimal refactoring. I suggest that you start with that and then try to change your coding standards so that constructor injection is allowed.
To get it working in your tests you can use the following implementation. It uses [ThreadStatic] to allow multiple tests to run at the same time.
public class TestDalFactory : IDalFactory
{
[ThreadStatic]
private static Dictionary<Type, object> _instances;
public static Dictionary<Type, object> DalInstances
{
get
{
if (_instances == null)
_instances = new Dictionary<Type, Object>();
return _instances;
}
}
public static TestDalFactory Instance = new TestDalFactory();
public T Create<T>() where T : class
{
return (T)_instances[typeof(T)];
}
}
Next in your tests you can configure the DAL factory to return a mock by doing the following:
[TestClass]
public class MyBusinessTests
{
[TestInitialize]
public void Init()
{
DalFactory.Instance = TestDalFactory.Instance;
}
[TestMethod]
public void do_some_testing_in_the_business()
{
TestDalFactory.Instance.DalInstances[typeof(CustomerDal)] = new MyNewMock();
//do the testing here
}
}
Using constructor injection of the DAL would allow you to stub the DAL layer. Ideally you would inject an interface. Mocking concrete classes is a bit of a pain with the tools I've used. Commercial mocking tools may well be better suited to mocking concrete classes but I've not used any of those.
class YourClass
{
private DAL customerDal;
public YourClass(DAL theDal)
{
customerDal = theDal;
}
public List<CustomerObject> FetchCustomersByName(CustomerObject obj)
{
// don't create the DAL here...
//Maybe other operations
List<CustomerObject> list = customerDal.FetchByName(obj.Name);
//Maybe other operations over list
return list;
}
}
[Test]
public void TestMethodHere()
{
// Arrange
var dalMock = Mock.Of<DAL>();
// setup your mock DAL layer here... need to provide data for the FetchByName method
var sut = new YourClass(dalMock);
// Act
var actualResult = sut.FetchCustomersByName(new CustomerObject());
// Assert
// Your assert here...
}

Using the Generic repository/Unit of work pattern in large projects

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>>.

Unit Testing Object Creation of Class with Hidden State (Query Object Pattern)

I have the following code:
public class Foo
{
public string Name { get; set; }
}
//query object pattern
public class FooQuery
{
private string _startsWith;
public FooQuery NameStartsWith(string startsWith)
{
_startsWith = startsWith;
return this;
}
public List<Foo> Execute(IQueryable<Foo> someContext)
{
if (!string.IsNullOrWhiteSpace(_startsWith))
someContext = someContext.Where(f => f.Name.StartsWith(_startsWith));
return someContext.ToList();
}
}
public interface IFooService
{
List<Foo> FindByNameStartsWith(string startsWith);
}
public class FooService : IFooService
{
private readonly IFooRepository _fooRepository;
public FooService(IFooRepository fooRepository)
{
_fooRepository = fooRepository;
}
public List<Foo> FindByNameStartsWith(string startsWith)
{
var query = new FooQuery().NameStartsWith(startsWith);
return _fooRepository.Find(query);
}
}
public interface IFooRepository
{
List<Foo> Find(FooQuery query);
}
public class FooRepository : IFooRepository
{
public List<Foo> Find(FooQuery query)
{
var someContext = new List<Foo>().AsQueryable(); //would be EF/Mongo, etc
return query.Execute(someContext);
}
}
Basically, I have a service "FooService" that news up a query object "FooQuery" and sets its state based on method parameters passed to it. The service then passes the query to the repository "FooRepository" where it does its data access thing. FooQuery purposefully does not expose its state via properties. It instead exposes methods for greater control. I need to unit test that FooService has created the query object correctly.
This is a challenge because FooQuery's state is not visible for unit testing. I see a couple of options, but all seem to smell:
Expose the state of FooQuery as read-only properties and, in unit tests, check those properties are valid when passed to the repository. (Checking the state of the query is technically possible via mocking frameworks with callbacks.) I don't like this because we now have to open up the state and modify the code just for testing purposes.
Keep the code as is and test that the results generated from the service method are the same as the results from the query object. I don't like this because it makes the unit tests larger, less conclusive and more redundant (I'd have to have a very similar test for the query object itself when checking for results)
Wrap FooQuery in an interface and create a factory to be injected into foo service. I can then test the proper methods where called on a mocked query. But, that still leaves me with a challenging test for the factory itself.
Any suggestions for testing/re-factoring this code to make it easier to test would be appreciated.
You could implement Equals on FooQuery then validate I you get the expected FooQuery via a mock'ed IFooRepository. This is a limited form your option #1.
You seem to have two responsibilities: getting an IQueryable from the datasource, and performing queries on it. Perhaps a simpler design makes sense?
public interface IFooRepository
{
IQueryable<Foo> GetFoo();
}
public FooService : IFooService
{
public List<Foo> FindByNameStartsWith(string startsWith)
{
return new FooQuery().StartsWith(startsWith).Execute(_fooRepo.GetFoo());
}
}
Now FooService is easy to test, and database specific logic is separated from all other logic.
[Test]
public void StartsWithFiltersFooFromRepository()
{
var fooFromRepository = new List<Foo> { new Foo {Name="yes1"}, new Foo {Name="no"}, new Foo {Name="yes2"} };
_fooRepMock.Setup(r=>r.GetFoo()).Returns(fooFromRepository);
var actual = _fooService.FindByNameStartsWith("yes");
Assert.That(actual, Is.EquivalentTo(new [] { fooFromRepository[0], fooFromRepository[2] }));
}

Unit Testing Interactions of methods in the same class in C#

I have the following code
public ClassToTest : IClassToTest
{
private readonly DBRepository rep;
public bool MethodA()
{
//Some logic
var result=MethodB();
//Do some logic against result;
}
public ResultType MethodB()
{
return Rep.GetResult();
}
}
If I want to Unit testing MethodA, what is the best practice to test the interaction between MethodA and MethodB? I am thinking to test MethodA like testing MethodB by mocking Database dependency Rep, just like MethodA has the following implementation
public bool MethodA()
{
//Some logic
var result=Rep.GetResult();
//Do some logic against result;
}
But it is not intuitive by checking the logic in the code and the test method. I am looking for a solution similar to the one mentioned here for Java.
unit testing composite service methods
But It is not working for C#.
One extra question, What if MethodB is private, does it make any difference for the Unit testing strategy?
Update: prefer not to change the structure of the class. like not making MethodB as virtual or Move the MethodB out of the class into another test
Thanks in advance.
You don't want to test the interaction between MethodA and MethodB, you want to test that MethodA will return the expected bool result, given some context.
The fact that MethodA calls MethodB is not germaine to this test; but the fact that Rep.GetResult() will at some point be called is.
As you mentioned, you can mock the dependency Rep, so it won't matter whether MethodB is public or private.
Mock and inject the dependency
Call MethodA
Assert against the result
You want to isolate your methods that you test, that is, you want to mock MethodB while testing MethodA, and vice versa.
Also, there is a testing paradigm to test the contract (or interface) of classes. In this paradigm, you wouldn't worry about non-public non-virtual methods. I tend to mock as much as I can.
I recommend you use a mocking framework (smug, rhino mocks, moq, easymock) Smug being the coolest, but it is not yet complete - I'll just show you the code below (this is how it would work without a mocking framework to help you).
public enum ResultType
{
Ok,
NotOk,
}
public abstract class DBRepository
{
public abstract ResultType GetResult();
}
public class ClassToTest
{
public DBRepository Rep { get; set; }
public virtual bool MethodA()
{
//Some logic
var result = MethodB();
//Do some logic against result;
return result == ResultType.Ok;
}
protected virtual ResultType MethodB()
{
return Rep.GetResult();
}
}
public class DBRepositoryMock : DBRepository
{
public ResultType FakeReturn { get; set; }
public override ResultType GetResult()
{
return FakeReturn;
}
}
public class ClassToTest_MethodA : ClassToTest
{
public ResultType MethodB_FakeReturn { get; set; }
protected override ResultType MethodB()
{
return MethodB_FakeReturn;
}
}
// tests
[TestMethod]
public void Test1()
{
ClassToTest mock = new ClassToTest_MethodA();
(mock as ClassToTest_MethodA).MethodB_FakeReturn = ResultType.Ok;
Assert.IsTrue(mock.MethodA());
}
// or using injection
[TestMethod]
public static void Test2()
{
var obj = new ClassToTest();
obj.Rep = new DBRepositoryMock { FakeReturn = ResultType.NotOk };
Assert.IsFalse(obj.MethodA());
}
[TestMethod]
public void MethodAReturnsTrueGivenSomeDataAndCondition()
{
IDBRepository mockRepo = new Mock<IDBRepository>(); //Create a mock of your repository call
ClassToTest subjectToTest = new ClassToTest(mockRepo.Object); //Inject the dependency
mockRepo.SetUp(r=>r.GetResult()).Returns(someSampleTestData); //You're setting up the object that might return you true to return when mock repo will be called, by default it returns the default or null usually
var result = subjectToTest.MethodA();
mockRepo.Verify(r=>r.GetResult(), Times.Once); //Make sure your repo method was called
Assert.IsTrue(result);
}
Something like this, using Moq as a sample mocking framework.

Categories

Resources