I'm doing some unit tests for an EntityEventListener from NHibernate, and I'm got stuck trying to mock FlushEvent or the EntityEntry.
As EntityEntry doesn't have a public constructor, and type Mock must be an interface, an abstract or non-sealed class.
EntityEntry ee = new EntityEntry(); //NOT
_entityEntryMock = new Mock<EntityEntry>(); //NOT
Without some elaboration, I can't say if this makes sense for you specifically, but when I hit a situation like this (a class that I can't mock with Moq and I can't build), I call in the big guns with an isolation framework. I generally use Moles, but there are other options like Typemock Isolator, and I think Moles itself is being replaced in the next .NET framework with a built-in isolator called "Fakes". But suffice it to say, you're attempting to use Moq for something it's not intended to do -- it just creates mocks "naturally" without serving as an isolation framework.
Related
I have the following method:
Void UpdateUser(User user){}
I need to check this method whether will work properly.
I've used a separate db to check this in unit testing. But many experienced people said if I use this method that won't be unit testing; that's integration testing.
But I don't know how to mock for unit testing.
The code written in the UpdateUser method, will try to update data using Entity framework.
If I mock (Actually I don't how to do this either), how this will work with entity framework?
Mocking means that you develop your software components (classes) in a way that any class with behaviour is used/consumed/called-upon as an interface (or abstract class). You program to an abstraction. Run-time you use something (service locator, DI container, factory, ...) to retrieve/create those instances.
The most common way is to use construction injection. Here is an excellent explanation of why one would use DI, and examples of how to do it.
In your case, your component that uses the Entity Framework (your repository for instance) must implement a repository-interface, and any class that uses your repository should use it as an interface.
This way, you can mock the repository in your unittests. Which means that you create a unit-test-repository class (which has nothing to do with any database or EF), and use that when you create the instance of the class that you want to unit-test.
Hopefully this helps. There are many source to be found. Personally I just read this book and I found it to be very good. This is the authors blog.
You can use transaction and rollback or create a test user try its update. Assert and then in the finally block delete the test user.
You can use mocking framework like moq, rhino etc. moq is quite easy and you can find many example that demonstrate moq with DI like unity framework.
If your class is like this
public class UserRepository()
{
Sqlcontext _context;
void UpdateUser(User user)
{
_context.Users.Add(user);
}
}
then this is not unit testable.
Although this is not a unit test, if you insist on connecting on database and testing it, you could change your function to
User UpdateUser(User user)
{
_context.Users.Add(user);
return user;
}
and test if
user.Id > 0
Here, you are basically just testing entity framework.
"I've used a separate db to check this in unit testing. But many
experienced people said if I use this method that won't be unit
testing; that's integration testing."
Those people are mistaken, despite their supposed experience. For some reason, the incorrect notion that unit tests are all about testing parts of your code in isolation has grown in popularity in recent years. In reality, unit testing is all about writing tests that act as a unit, in other words they exist in isolation and the result of one unit test cannot influence another test.
If your UpdateUser method directly accesses EF, then as long as you ensure the database is guaranteed to be rolled back to its starting state at the end of each test, then you have unit tests. However, setting the database up for each test and ensuring it can be reliably rolled back can be a lot of work. That is why mocks are often used. Other answers have covered mcoking EF, so I won't go over that.
To greatly simplify your tests, you could have an extrapolation layer between UpdateUser and EF. In other words, the UpdateUser class is supplied with an instance of an interface, which is its gateway into EF. It doesn't talk to EF directly. To then mock EF, you simply supply a mocked implementation of the interface. This then pushes the need to test against EF down into a more basic layer, with more basic CRUD-like behaviours.
A non official trick, not-best-practice can be to use an in-memory database (context) for the time of testing.
Use transaction and rollback your transaction at the end of test
Is there a standard method for unit testing code where dependencies do not implement interfaces? For instance, the System.Net.Http namespace only exposes concrete classes. If I'm trying to unit test a class which relies upon one of the concrete classes in System.Net.Http, should I merely construct an instance of, say, HttpRequestMessage, set it's properties and then supply this newly constructed object to the system under test? Would it make sense to subclass HttpRequestMessage and have it implement a custom interface which could then be mocked/stubbed?
The recommended practice is to wrap this object in a class of your creation, which itself implements an interface. You would then use this wrapper class in your code, and you can then supply mocked versions of this wrapper in place of the real class. You would not subclass it using this method, but rather contain it and use delegation (not to be confused with delegates!) to forward each method.
For instance, you might create a class HttpRequestMessageWrapper that inherits from IHttpRequestMessage (that you define, including all the public properties of HttpRequestMessage.. although you could probably get by with only implementing the properties you use).
Alternatively, you can use a testing framework that supports shims, which is a framework that essentially does this wrapper for you and replaces calls to the objects with shim versions. Microsoft Fakes (introduced in VS 2012 MS Test) does this.
Shims are typically used to replace common framework calls, such as DateTime.Now so you can supply a specific value during tests.
I would suggest you have a look at: AutoFixture http://autofixture.codeplex.com/ It helps you construct the object in the way you want. In your example, HttpRequestMessage, you can customize the fixture: fixture.Customize<HttpRequestMessage>(c => {});
There are many examples out there using AutoFixture in Unit Testing. Or you can post the code you want to test here and i can try to help.
Another good tool for testing legacy code is Typemock
This question already has answers here:
Non Interface dependent Mocking Frameworks for C#
(4 answers)
Closed 9 years ago.
I want to mock a particular method of a class, problem i am facing while mocking is that class does not have any interface and also that method is not virtual.
Can any one suggest any other way to implement mocking.
Any help will be appreciated.
Thanks in advance
Option 1: TypeMock Isolator or something similar, which allows deeper messing with the code than normal mocking.
Option 2: (Preferred if possible) Alter the design, e.g. by introducing an interface and creating a delegating implementation which just calls into the existing test-unfriendly class. You can then depend on the interface, mock it in tests, and delegate to the "real" implementation for production.
This is assume you really should be mocking the class, of course. You shouldn't automatically mock everything your code uses - I tend to think of mocking "services" of some description, whereas I wouldn't mock (for example) List<T>.
I suggest refactoring your code ;) All mocking frameworks which creates mock by deriving from mocked class requires methods to be virtual (this is more CLR requirement rather than mocking framework).
To mock non-virtual methods you can use profiler-based frameworks like Moles or TypeMock Isolator, however this requires to run test runner using special runner which will attach CLR profiler to process
There are unit testing frameworks such as TypeMock Isolator that allow you to mock non-virtual members.
To purely mock out a legacy class I would do the following:
Create an interface containing the ONLY public members that I intend on using.
eg.
public interface IDbContext {
int SaveChanges();
}
If the target legacy class is sealed then I'd create a proxy/decorator class which implements the new interface and just invoked the underlying methods/properties.
public class MyDbContextProxy : IDbContext {
DbContext _context = null;
public MyDbContextProxy(DbContext interceptedContext) {
_context = interceptedContext;
}
// decorated method
public int SaveChanges() {
_context.SaveChanges();
}
}
If the target legacy class is not sealed I'd create a descendant of the target and implement the interface. The class auto adheres to the interface.
public class MyDbContextProxy : DbContext, IDbContext {
// child adheres to interface by inheritence
}
Now you can Mock out IDbContext.
Right now there is something like Fakes Framework in VS2012. It's the successor of Moles (also able to mock classes etc. like TypeMock). It's available only in Ultimate edition, so I don't thnink it's worth Ultimate's price.
But, I'd like to discuss problem with mocking classes from other perspective.
Is it a good approach to mock classes instead of interfaces or it's some kind of a bad smell? I've never used TypeMock (it's too expensive to even consider it in small company), but people claims it's a bit "too powerful" so I'd like to use Moq/RhinoMocks, but sometimes I'd like to mock/fake one method and leave the others. It's my bad way of thinking about mocking/faking methods during tests? or it is sometimes required?
I am new to mocking so I might have it totally wrong here but I believe that most mocking frameworks are interface dependent. Unfortunately most of our code is not using an interface. Now the other day I saw a Mocking framework in Java that reproduced the byte code of a class\object as to not call its internal methods but you could still test that it WAS calling these methods.
My question is: does .Net have any mocking frameworks that can do a similar thing? I am looking for something free and I don't want something that requires methods to be virtual or abstract.
Microsoft Research has developed Moles for this, which is a part of Pex but can be installed independently. And it's free. There's a good introductory article (pdf) on the website that explains how to mock a static method. It takes some time before they get to the stuff you want (page 16, Task 3).
Here and here (Channel 9) you can find an example on how to stub DateTime.Now. Using Moles, you can mock anything you want.
TypeMock Isolator can mock any .NET class, but it's not free (or cheap, even). I'm not sure how it works exactly, but it achieves the same end result.
But most of the mocking frameworks don't depend exclusively on interfaces; they should be able to handle concrete classes just as well, although they'll only be able to override virtual or abstract methods.
You can use classes instead of interfaces with both Moq and Rhino.Mocks, but the mocked methods must be virtual. Mark Rushakoff's answer on TypeMock is correct (+1).
The best option is to refactor your existing code for testability (which may take time). I'd recommend reading Working Effectively with Legacy Code by Michael Feathers.
A lot of .NET mocking frameworks use Castle Dynamic Proxy to create mocks at runtime. Hence the limitation of only allowing interface/virtual methods to be mocked comes from Castle and I think is rooted in CLR. Both MOQ and RhinoMocks are able to mock virtual methods, which is as good as it gets.
Both classes and interfaces can be
proxied, however only virtual members
can be intercepted.
My advice would be to start creating abstract bases for those classes that need to be mocked and have the concrete class extend it. Then the abstract base can be passed around and mocked. It really is a refactoring exercise that is not overly complex.
I've been writing some providers in c# that inherit from the providerbase class. I've found that it's hard to write tests that use the providers as most mocking frameworks will only allow you to mock an interface.
Is there any way to mock a call to a provider that inherits from providerbase?
If not, is there a pattern that I can use to implement mocking of providers?
Mocking frameworks should be able to create for you a mock object based on a class, as long as it's got virtual members.
You may also want to take a look at Typemock
I know Rhino mocks can mock classes too, most other mocking frameworks should have no problems with this either.
Things too keep in mind: The class can't be sealed. You need to mark methods you want to mock virtual and the class needs a constructor with no arguments this can be protected, private won't work. (just tried this out)
Keep in mind that the mocking framework will just create a class that inherits from your class and creates an object of that type. So constructors will get called. This can cause unexpected behaviour in your tests.
RhinoMocks or Moq will create test doubles for classes as well as for interfaces. The type has to have virtual methods or be abstract though. The Typemock isolator gets around this.
I'd suggest that the objects you want to mock probably should be abstract (dependency inversion principle).