Mocking a Linq2Sql DataContext - c#

I have a Lin2Sql DataContext that I am using to get all my data from a sql database however I am struggling to find a way to successfully Mock this so that I can create relevant Unit Tests.
In my data access objects that I am wanting to test I am refreshing the context each time and I am finding it difficult to find a simple suitable way to mock this.
Any help with this matter will be greatly appreciated.

Mocking the linq-to-sql context is indeed a huge task. I usually work around it by letting my unit tests run against a separate database copy, with data specially crafted to fit the unit tests. (I know it can be argued that it's no longer unit tests, but rather integration tests, but I don't care as long as I get the code tested).
To keep the database in a known state I wrap each test in a TransactionScope which is rolled back at the end of the test. That way the state of the database is never changed.
A sample test method looks like this:
[TestMethod]
public void TestRetire()
{
using (TransactionScope transaction = new TransactionScope())
{
Assert.IsTrue(Car.Retire("VLV100"));
Assert.IsFalse(Car.Retire("VLV100"));
// Deliberately not commiting transaction.
}
}
The code is from a blog post about the method I wrote some time ago: http://coding.abel.nu/2011/12/using-transactions-for-unit-tests/

Since you request a way to mock a DataContext I assume that you really want to do some unit tests and not integration tests.
Well, I will tell you how to accomplish this, but first I would like to encourage you to read the following links, they are all about writing clean testable code.
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
And check the links from this response:
https://stackoverflow.com/a/10359288/1268570
Watch the clean code talks from Misko Hevery (given to the Google people)
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
http://www.youtube.com/watch?v=-FRm3VPhseI&feature=player_embedded
http://www.youtube.com/watch?v=4F72VULWFvc&feature=player_embedded
One thing that I used to repeat to myself and to my fellows at work, is that anyone can write a unit test, because they are silly easy to write. So a simple test is essentially all about making some comparisons and throw exceptions if the results fails, anyone can do that. Of course, there are hundreds of frameworks to help us write those tests in an elegant way. But the real deal, and the real effort shroud be put on learn how to write clean testable code
Even if you hire Misko Hevery to help you write tests, he will have a real hard time writing them if your code is not test-friendly.
Now the way to mock a DataContext objects is: do not do it
Instead wrap the calls using a custom interface instead:
public interface IMyDataContextCalls
{
void Save();
IEnumerable<Product> GetOrders();
}
// this will be your DataContext wrapper
// this wll act as your domain repository
public class MyDataContextCalls : IMyDataContextCalls
{
public MyDataContextCalls(DataClasses1DataContext context)
{
this.Context = context;
}
public void Save()
{
this.Context.SubmitChanges();
}
public IEnumerable<Product> GetOrders()
{
// place here your query logic
return this.Context.Products.AsEnumerable();
}
private DataClasses1DataContext Context { get; set; }
}
// this will be your domain object
// this object will call your repository wrapping the DataContext
public class MyCommand
{
private IMyDataContextCalls myDataContext;
public MyCommand(IMyDataContextCalls myDataContext)
{
this.myDataContext = myDataContext;
}
public bool myDomainRule = true;
// assume this will be the SUT (Subject Under Test)
public void Save()
{
// some business logic
// this logic will be tested
if (this.myDomainRule == true)
{
this.myDataContext.Save();
}
else
{
// handle your domain validation errors
throw new InvalidOperationException();
}
}
}
[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod()
{
// in this test your mission is to test the logic inside the
// MyCommand.Save method
// create the mock, you could use a framework to auto mock it
// or create one manually
// manual example:
var m = new MyCommand(new MyFakeDataContextFake());
m.Invoking(x => x.Save())
//add here more asserts, maybe asserting that the internal
// state of your domain object was changed
// your focus is to test the logic of the domain object
.ShouldNotThrow();
//auto mock example:
var fix = new Fixture().Customize(new AutoMoqCustomization());
var sut = fix.CreateAnonymous<MyCommand>();
sut.myDomainRule = false;
sut.Invoking(x => x.Save())
.ShouldThrow<InvalidOperationException>();
}
public class MyFakeDataContextFake : IMyDataContextCalls
{
public void Save()
{
// do nothing, since you do not care in the logic of this method,
// remember your goal is to test the domain object logic
}
public IEnumerable<Product> GetOrders()
{
// we do not care on this right now because we are testing only the save method
throw new NotImplementedException();
}
}
}
Notes:
When you declare your IMyDataContextCalls interface you are actually abstracting the use of a DataContext, therefore this interface should contain only POCO objects (most of the time), if you follow this approach your interfaces will be decoupled from any undesired dependency.
In the specific MyDataContextCalls implementation, you are explicitly using a DataClasses1DataContext context, but you are free to change the implementation at any time and that won't affect your external code, and that's because you are always working with the IMyDataContextCalls interface instead. So at any time you could change for example this implementation for another one using the wonderful NHibernate =) or the poor ef or a mock one
At last, but not least. please double check my code, and you will notice that there are no new operators in the domain objects. This is a rule of dumb when writing test friendly code: decouple the responsibility of creating objects outside of your domain objects
I personally use three frameworks on every project and on every test I write, I really recommend them:
AutoFixture
Moq
FluentAssertions
For example, in the code above, I showed you how to write a manual fake for your repository, but that clearly is something we do not want to do in a real project, imagine the number of objects you would have to code in order to write your tests.
Instead use the power of AutoFixture combined with Moq:
This line: var m = new MyCommand(new MyFakeDataContextFake());
Will become:
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var sut = fixture.CreateAnonymous<MyCommand>();
And that's it, this code will automatically create mocks for all the objects needed in the constructor of MyCommand.

In short, you don't mock DataContext. You extract interface from it and mock that interface using some collections for entity sets, and then verify contents of those collections.

Related

Mocking out a specific method during a unit test

I'm relatively new to unit testing, and brand new to Moq. I have been tasked with writing up some unit tests for some pre-existing code.
I am struggling with the following method, as it makes a call to model.importing.RunJob, which as the name suggests, kicks off a job.
Obviously, I don't want it to actually DO the job, I just want to know that it's called the method.
How would I go about achieving this (ideally avoiding any code changes):
public ActionResult ImportsAndLoads(ImportsAndLoadsViewModel importsAndLoadsModel)
{
Initialise(importsAndLoadsModel);
LoadData(importsAndLoadsModel);
if (importsAndLoadsModel.ActionToPerform == "RunJob")
{
using (var model = new Model())
{
List<Message> lstMessage;
model.importing.RunJob((Jobs)Enum.ToObject(typeof(Jobs), importsAndLoadsModel.SelectedJob), out lstMessage);
importsAndLoadsModel.lstMessages = lstMessage;
}
}
return View(importsAndLoadsModel);
}
As has been discussed in the comments on your question, you can't really test your ImportsAndLoads method in isolation in its current form, using Moq. If you are using a high enough version of Visual Studio, then you may be able to test the method using Shims, however if you're not already using this in your project, it's probably not the right way to go.
As it stands, your code is a little confusing. It's a bit weird having a class called Model, that you're creating, in order to access a property in order to call a RunJob method. If this really is the code, then you might want to encourage the team to revisit the Model class.
One of the suggestions was that you inject your Model dependency instead of creating it (or inject a factory and call out to the factory for creation). This would be the preferable way to go, however it's not a trivial change in approach and really your team needs to buy into it as an approach rather than you making the change as a one-off.
If you aren't using an IOC container already (AutoFac, CastleWindsor, Ninject), then you may want to consider using one. They will make switching to dependency injection easier. If you want to do it by hand, then you can do, but it's harder.
Without knowing about the structure of more of your classes, it's hard to give a complete example, but one approach might be the following:
// Create an importer interface
public interface IImporter {
void RunJob(Jobs job, out List<Message> listMessages);
}
// Implement it in a concrete class
public class Importer : IImporter{
public void RunJob(Jobs job, out List<Message> listMessages) {
// Do whatever it is it does.
}
}
// Modify the constructor of your controller to allow the IImporter
// interface to be injected. Default to null if not supplied, so that
// it can still be crated without parameters by the default MVC plumbing
public class ImportController : Controller
{
private IImporter _importer;
public ImportController(IImporter importer = null) {
// If importer not injected, created a concrete instance
if (null == importer) {
importer = new Importer();
}
// Save dependency for use in actions
_importer = importer;
}
// Use the injected importer in your action, rather than creating a model
public ActionResult ImportsAndLoads(ImportsAndLoadsViewModel importsAndLoadsViewModel)
{
List<Message> listMsgs;
_importer.RunJob(Jobs.One, out listMsgs);
importsAndLoadsViewModel.lstMessages = listMsgs;
return View(importsAndLoadsViewModel);
}
}
This would then allow you to write a test to validate that importsAndLoadsViewModel has been updated as expected, using a test like this:
[Test]
public void TestModelMessagesAreUpdatedFromJobRunner() {
var mockImporter = new Mock<IImporter>();
List<Message> expectedMessages = new List<Message>();
mockImporter.Setup(x=>x.RunJob(It.IsAny<Jobs>(), out expectedMessages));
var model = new ImportsAndLoadsViewModel();
// Inject the mocked importer while constructing your controller
var sut = new ImportController(mockImporter.Object);
// call the action you're testing on your controller
ViewResult response = (ViewResult)sut.ImportsAndLoads(model);
// Validate the the model has been updated to have the messages
// returned by the mocked importer.
Assert.AreEqual(expectedMessages,
((ImportsAndLoadsViewModel)response.Model).lstMessages);
}
This is simplification of what would need to be done / tested to demonstrate an approach. One of the issues to be aware of with injecting dependencies is that it's quite easy to end up creating abstractions of abstractions, pushing the actual logic deeper and deeper into your code, only to find that you've just pushed the problem deeper and that you still don't know how to test a particular piece of logic because in essence it hasn't changed.

How to test methods where DBContext is created?

I don't have a lot of experience with unit testing. For example I have simple method in the application:
public void GetName()
{
UserRights rights = new UserRights(new DatabaseContext());
string test = rights.LookupNameByID("12345");
Console.WriteLine(test);
}
In this case I'm able to test all methods of UserRights class by passing mocked DatabaseContext, but how can I test GetName() method? What is the best practice? Where DatabaseContext should be created?
If you want to test the GetName method in a properly isolated way (i.e. a Unit Test) then you can't use new to create the UserRights instance in the method itself; because a test is really just another client of the code, therefore it can't (and shouldn't) know anything about how GetName works internally
So what this means is that for a proper Unit Test you must be able to replace all dependencies of a method with ones that the client fully controls - in the case, the code in the Unit Test is the client.
In your posted code, the client code has no control at all over UserRights nor DatabaseContext, so this is the first thing that has to change.
You need to rework your code so that the UserRights implementation can be supplied by the client. In fact once that's done, the problem about where DatabaseContext comes from is actually irrelevant for the Unit test because it doesn't care about how UserRights itself performs its tasks!
There are a number of ways of doing this; you can use Mocks or Stubs, you can use Constructor or Method injection, you could use a UserRights factory. Here is an example of using very simple stubs which IMHO is the best way to start and avoids having to learn a Mocking framework -- I personally would use Mocks for this but that's cos I am lazy :)
(code below assumes the class containing GetName is called "UserService", and uses xUnit framework; but MSTest will work just fine too)
Let's suppose you have control over the code of UserService so you can make the LookupNameByID method virtual (if you can't, then you may have to go the route if interfaces and mocks)
public class UserRights
{
public virtual LookupNameByID(string id)
{
//does whatever a UserRights does.
}
}
public class UserService
{
readonly UserRights _rights;
public UserService(UserRights rights)
{
_rights=rights; //null guard omitted for brevity
}
public string GetName(string id)
{
return _rights.LookupNameByID(id);
}
}
now in your unit test code suppose you create a sub-class of UserRights like this:
public class ExplodingUserRights: UserRights
{
public override string LookupNameByID(string id)
{
throw new Exception("BOOM!");
}
}
Now you can write a test to see how GetName reacts when something bad happens:
[Fact]
public void LookupNameByID_WhenUserRightsThrowsException_DoesNotReThrow()
{
//this test will fail if an exception is thrown, thus proving that GetName doesn't handle exceptions correctly.
var sut = new UserService(new ExplodingUserRights()); <-Look, no DatabaseContext!
sut.GetName("12345");
}
and one for when good things happen:
public class HappyUserRights: UserRights
{
public override string LookupNameByID(string id)
{
return "yay!";
}
}
[Fact]
public void LookupNameByID_ReturnsResultOfUserRightsCall()
{
//this test will fail if an exception is thrown, thus proving that GetName doesn't handle exceptions correctly.
var sut = new UserService(new HappyUserRights());
var actual = sut.GetName("12345");
Assert.Equal("yay!",actual);
}
and so on. Note that we never went anywhere near DatabaseContext, because that's a problem you only have to solve when you unit test the UserRights class itself. (and at that point I would probably recommend using Jeroen's advice from his linked article,and do an integration test, unless setup of a database for each test is something you can't or won't do, in which case you need to use interfaces and mocks)
Hope that helps.
Separating your codes reliance on DB Context is something you will want to investigate, this can be accomplished using the Repository pattern. Since you're passing the DB Context into your objects constructor, in this case UserRights, you can pretty easily change your code to take in an Interface (or simply add an overloaded contructor to the class that accepts an interface, then call that in your unit tests, preserving any existing code). There are lots of ways to get this done, a quick Google search yielded the following article:
http://romiller.com/2012/02/14/testing-with-a-fake-dbcontext/
http://www.codeproject.com/Articles/207820/The-Repository-Pattern-with-EF-code-first-Dependen
Once your class can accept an interface rather than (or as an alternative to) the strongly typed DB Context object you can use a Mock framework to assist with testing. Take a look at Moq for examples on how to use these in your unit tests https://github.com/Moq/moq4/wiki/Quickstart
Be Aware: Moq can become difficult to work with when your tests require data that is related via foreign keys, the syntax can be complicated to get your head around. One thing to watch out for is the temptation to make changes to your code just to make a unit test easier to set up, while there may be value in making this change it also may indicate that you need to re-think your unit test rather than violate your applications architecture and/or design patterns

Unit testing for method using database bounded when application started

I use NUnit for my unit-testing. In my current project, I have a problem in which almost all of the functions I want to test are connected to the database. Meanwhile, the database is bounded when the application is started.
I am so confused now, I have read regarding mock unit-testing, but don't know exactly how to handle this problem. Any solution for me here?
To make things harder, this database is static, not as parameter of my method... This makes me so confused
You might want to review the architecture of your application. Make sure the database layer is loosely coupled, for example by using interfaces. This will make it possible to write stubs or mocks for your database layer.
The normal solution to this is to keep your data layer in a separate class that implements a well-known interface. For instance:
public interface IDataLayer
{
IEnumerable<Customer> GetAllCustomers();
Order GetOrderById(int id);
}
You will implement the interface as normal for your actual data access
public class SqlServerDataLayer : IDataLayer
{
// implementation
}
But in your tests, you can now use a mocking framework like Moq or RhinoMocks to set up a mock data layer that returns test data. This ensures you are only testing how your classes use the data, which is ideal.
[Test]
public void TestGettingCustomersRefreshesViewModel()
{
//arrange
var mockDb = new Mock<IDataLayer>();
mockDb.Setup(db => db.GetAllCustomers()).Returns(new List<Customer>());
underTest.DataRepository = mockDb.Object;
//act
underTest.GetCustomerCommand.Execute();
//assert
Assert.That(underTest.CustomerList != null);
}

How to use mocks in this case?

Here is my problem:
I have an n-tiers application for which I have to write unit tests. Unit tests are for the business layer.
I have a method to test called Insert() and this one use two protected methods from inheritance and call directly a method from Data access layer.
So I have made a mock object for the DAL. But here is the point, in a (edit :) protected method from inheritance, It will use another object from DAL! It seems it is not possible to mock this one!
Here is the method for test code:
public int Insert(MYOBJECT aMyObject)
{
//first inherited method use the FIRSTDALOBJECT so the mock object --> No problem
aMyObject.SomeField= FirstInherited();
//Second inherited method (see after) --> my problem
aMyObject.SomeOtherField = SecondInherited();
// Direct access to DALMethod, use FIRSTDALOBJECT so the mock -->No Problem
return this.FIRSTDALOBJECT.Insert(aMyObject);
}
Here is the SecondInherited method:
protected string SecondInherited ()
{
// Here is my problem, the mock here seems not be possible for seconddalobject
return ( new SECONDDALOBJECT Sdo().Stuff());
}
And here is the unit test method code :
[TestMethod()]
public void InsertTest()
{
BLLCLASS_Accessor target = new BLLCLASS_Accessor();
MYOBJECT aMyObject = new MYOBJECT { SomeField = null, SomeOtherField = 1 };
int expected = 1;
int actual;
//mock
var Mock = new Mock<DAL.INTERFACES.IFIRSTDALOBJECT>();
//Rec for calls
List<SOMECLASS> retour = new List<SOMECLASS>();
retour.Add(new SOMECLASS());
//Here is the second call (last from method to test)
Mock
.Setup(p => p.Insert(aMyObject))
.Returns(1);
// Here is the first call (from the FirstInherited())
Mock
.Setup(p => p.GetLast())
.Returns(50);
// Replace the real by the mock
target.demande_provider = Mock.Object;
actual = target.Insert(aMyObject);
Assert.AreEqual(/*Some assertion stuff*/);
}
Thank you for reading all the question :-) Hope it is clear enough.
Your text seems to say that SecondInherited is private, while in the code example it is protected. Anyway, if it is not protected, I would suggest changing its access qualifier as the first step.
You can create a subclass solely for testing purposes, and override SecondInherited there to avoid creating SECONDDALOBJECT and just return some value suitable for your tests.
This way you can write your first unit test(s) with minimal changes to the class being tested, thus minimizing the chances of breaking something. Once you have the unit tests in place, these allow you to do more refactoring safely, eventually achieving a better (more testable / mockable) design, such as using Dependency Injection, or a Factory. (I would probably prefer an Abstract Factory over Factory Method here, as the latter would practically force you to keep subclassing the tested class).
The fundamental, highly recommended book for learning this technique (and many more) is Working Effectively With Legacy Code.
No chance to mock this with MOQ.
You have two options:
Use TypeMock or Moles to mock the SECONDDALOBJECT class
Refactor the code, so the instance of SECONDDALOBJECT isn't created in the way it is, but in a way that can be mocked (Factory method, DI, ...) (prefered!)

Unit Testing practice with Linq to SQL

I'm trying to wrap my head around unit testing, and I've encountered a behavior that I'm unsure of:
"Can Backup Inventory"
Basically, the "Inventory" table is copied to the "InventoryHistory" table, and given a time-stamp of when the backup occurred ("HistoryDate").
Here's the code for backing-up inventory:
DateTime historyDate = DateTime.Now;
MyDataContext db = new MyDataContext();
db.GetTable<InventoryHistory>().InsertAllOnSubmit(
db.GetTable<Inventory>()
.Select(i => new InventoryHistory
{
ID = i.ID,
ItemName = i.ItemName,
/* etc, etc, etc */
HistoryDate = historyDate
})
);
My questions are:
Should/Can this behavior be broken down into smaller unit-testable parts?
Since I am testing against a dedicated test database, should I be using a mocking tool and following the abstract factory pattern for any "repositories"?
The question I would ask is that is this really a unit test? A unit test would consider mocked Table<TEntity> instances, because we're not concerned with the actual data, rather that the mechanism of creating the items is correct.
In your snippet above, it seems that you are unit testing the Linq methods themselves, not any specific code you have written yourself.
As for your last question, one of the fundamental mistakes made with mocking is the assumption of what to test when mocking. Typically you would be mocking a something consumed by the type you want to test. E.g.:
public ICalculatorService
{
int Add(int a, int b);
}
[Test]
public void CannAdd()
{
var mock = Mock<ICalculatorService();
mock.Setup(m => m.Add(It.IsAny<int>(), It.IsAny<int>()))
.Returns(100);
var service = mock.Object;
Assert(service.Add(1, 2) == 100); // Incorrect
}
The above is a pointless test, because I am testing that it is returning exactly what I have told it to. I'm not testing the Moq framework here, I need to test my code, so I would need to be testing the consumer:
public class Calculator
{
private readonly ICalculatorService _service;
public Calculator(ICalculatorService service)
{
_service = service;
}
public int Add(int a, int b)
{
return _service.Add(a, b);
}
}
[Test]
public void CannAdd()
{
var mock = Mock<ICalculatorService();
mock.Setup(m => m.Add(It.IsAny<int>(), It.IsAny<int>()))
.Returns(100);
var calculator = new Calculator(mock.Object);
Assert(calculator.Add(1, 2) == 100); // Correct
}
That's more like it (although a simplistic example). I am now testing the Calculator consumer itself, not the consumable. In your example, even if you were mocking your DataContext to return dummy instances of Table<TEntity>, what real benefits do you get?
Realistically you'd probably create a repository, e.g. an IInventoryRepository, and create a consumer of that repository (could be a domain model, a controller, etc). Then through testing, you'd mock that repository, and test your consumer.
This looks like a fairly atomic operation to me, not much opportunity for breaking it apart.
Unit testing does not hit the database- that's integration testing. If you want a good unit test for this, you would test for behavior- in this case, that the history is backed up when it's supposed to be.
By way of full disclosure, I'm only just starting to learn EF and LINQ and the best way to test them, so you may get some more useful information regarding them in particular, so these are just general testing answers.
1.
I can't see a way that this can be further broken down to be isolated for unit testing, apart from:
ID = i.ID,
ItemName = i.ItemName,
/* etc, etc, etc */
HistoryDate = historyDate
being refactored into a seperate method to be unit tested as the only other code are LINQ calls, which MS are responsible for testing.
2.
I don't think you'd be able to introduce a seam to isolate it with the abstract repository factory pattern, since you're calling into a datacontext.
I'm not sure whether you should fake this (and since you'd be testing against it will be a mock proper - a fake that you test against, a fake that you don't test against is a stub) but since it's calling into a test server, you can make it an automated integration test since the functionality involves the interaction with the data store.
At first, method you describe looks simply and I'm not sure it needs any unit tests.
But, if you want to decompose it, you may do this:
Extract method for getting list of inventories for backup
IQueryable GetInventoryForBackup(this DataContext context)
{
return context.GetTable();
}
Extract method to convert Inventory to InventoryHistory
IEnumerable ToInventoryHistory(this IEnumerable data, DateTime historyDate)
{
return data.Select(i => new InventoryHistroy { ID = i.Id ....
}
Extract method to save sequence of InventoryHistory
void SaveHistory(IEnumerable data)
{
dataContext.InsertAllOnSubmit(data);
dataContext.SubmitChanges();
}
Now you have seemsful methods and you can easy write unit tests for.

Categories

Resources