Mocking using Moq in c# - c#

I have the following code:
public interface IProductDataAccess
{
bool CreateProduct(Product newProduct);
}
Class ProductDataAccess implements that interface.
public class ProductBusiness
{
public bool CreateProduct(Product newProduct)
{
IProductDataAccess pda = new ProductDataAccess();
bool result = pda.CreateProduct(newProduct);
return result;
}
}
In this case, how to create unit test for CreateProduct method by mocking the IProductDataAccess interface? I thought of having an public instance of IProductDataAccess within ProductBusiness and initialize it using Mock<IProductDataAccess> object but it is not a good practice to expose the data access to the UI layer. Can any one help me?

Classic example which demonstrates that if you cannot unit test a particular component, REFACTOR it!
This is why I love what any mocking framework enforces you to do - write decoupled code.
In your example, the ProductBusiness class is tightly coupled with the ProductDataAccess class. You could decouple it using (like most of the answers suggest) dependency injection. By doing so, you would end up depending on the IProductDataAccess abstraction and not on any concrete implementation of it.
Another point to note, when you are writing tests/specifications for the business layer, you would typically want to test the "behavior" and not the "state". So, although you could have asserts that verify if "true" was returned, your tests should really test if the expected data access calls that were set using MOQ were actually executed using the .Verify API of MOQ.
Try adding behavior tests where you expect an exception to be thrown (using the ".Throws" API) by the data access layer and check if you need any special handling at the business layer.
Like Kevin suggests, the following implementation of ProductBusiness will work:
public class ProductBusiness
{
private readonly IProductDataAccess _productDataAccess;
public ProductBusiness(IProductDataAccess productDataAccess)
{
_productDataAccess = productDataAccess;
}
public bool CreateProduct(Product newProduct)
{
bool result=_productDataAccess.CreateProduct(newProduct);
return result;
}
}
and use any xunit testing framework to write the test as:
var mockDataAccess = new Mock<IProductDataAccess>();
mockDataAccess.Setup(m => m.CreateProduct(It.IsAny<Product>())).Returns(true);
var productBusiness = new ProductBusiness(mockDataAccess.Object);
//behavior to be tested

You should inject IProductDataAccess interface as a dependency:
public class ProductBusiness
{
private IProductDataAccess _productDataAccess;
public ProductBusiness(IProductDataAccess productDataAccess)
{
_productDataAccess = productDataAccess;
}
public bool CreateProduct(Product newProduct)
{
bool result = _productDataAccess.CreateProduct(newProduct);
return result;
}
}
Then you can replace it with a mock in your tests:
var productDataAccess = new Mock<IProductDataAccess>();
var productBusiness = new ProductBusiness(productDataAccess.Object);

With the way that you have currently designed your ProductBusiness class there is no way of changing the IProductDataAccess implementation using a mock. A recommended pattern for this is dependency-injection where you take the dependencies of a type through the constructor. So your class becomes:
public class ProductBusiness
{
private readonly IProductDataAccess _productDataAccess;
public ProductBusiness(IProductDataAccess productDataAccess)
{
_productDataAccess = productDataAccess;
}
public bool CreateProduct(Product newProduct)
{
bool result = _productDataAccess.CreateProduct(newProduct);
return result;
}
}
Now you are in a position to test your class by using a mocking framework like moq. For example:
var mockDataAccess = new Mock<IProductDataAccess>();
mockDataAccess
.Setup(m => m.CreateProduct(It.IsAny<Product>()))
.Returns(true);
var productBusiness = new ProductBusiness(mockDataAccess.Object);
// ... test behaviour here
Now you can change how the mock behaves in your setup step and make sure that your CreateProduct method is behaving correctly.
I would also look at a dependency injection framework like castle-windsor. A dependency injection framework can automatically resolve dependencies meaning creating a new type is much easier as you don't have to manually new everything up. Also it means that you can change which implementation is used in one place and it changes everywhere.

You shouldn't instantiate a concrete ProductDataAccess inside your CreateProduct method.
Instead, IProductDataAccess should be an injectable dependency. This can be done in one of two ways:
Property injection:
public class ProductBusiness
{
IProductDataAccess Pda {get; set;}
}
var productBusiness = new ProductBusiness();
productBusiness.Pda = new ProductDataAccess();
productBusiness.Pda = new MockProductDataAccess();
Or constructor injection:
public class ProductBusiness
{
private readonly IProductDataAccess _pda;
public ProductBusiness(IProductDataAccess pda)
{
_pda = pda;
}
}
var productBusiness = new ProductBusiness(new ProductDataAccess());
var productBusiness = new ProductBusiness(new MockProductDataAccess());
Constructor injection is usually the recommend approach.
Property injection is used for optional dependencies (e.g., instantiate a concrete NullLogger by default in the constructor, and use the property to optionally inject a working logger).

Related

Creating a Moq of a static extension method from LLBLGen

i'm trying to use Moq to mock an extension method from the IDataAccessAdapter interface from LLBLGen. Here is FetchQueryAsync the extension method.
Doing so gave me the error that i can't Mock static extension methods. However there is no way i can change the code. So i tried creating a wrapper class, yet i had no success doing that either because i do not know how to apply it.
In the method Fetch, i want FetchQueryAsync to return an object i specified during the test and not actually execute the query.
public class QueryHandler
{
private IDataAccessAdapterProvider dataAccessAdapterProvider;
public QueryHandler(IDataAccessAdapterProvider provider)
{
this.dataAccessAdapterProvider = provider;
}
private async Task<T> Fetch(DynamicQuery<T> query)
{
using (IDataAccessAdapter adapter = dataAccessAdapterProvider.Provide()
{
result = await adapter.FetchQueryAsync(query)
}
}
}
public class DataAccessAdapterProvider : IDataAccessAdapterProvider
{
public IDataAccessAdapter Provide()
{
var adapter = new DataAccessAdapter();
return adapter;
}
}
So in my Unit Test i have this:
List<int> il = new List<int>();
Mock<IDataAccessAdapterProvider> mock = new Mock<IDataAccessAdapterProvider>();
mock.Setup(m => m.Provide()
.FetchQueryAsync<int>(It.IsAny<DynamicQuery<int>>()))
.ReturnsAsync(il);
This won't work however because it's not supported.
So i tried wrapping the method as such.
interface IWrap
{
Task<List<TElement>> FetchQueryAsync<TElement>(IDataAccessAdapter adapter, DynamicQuery<TElement> query);
}
public class Wrap : IWrap
{
public async Task<List<TElement>> FetchQueryAsync<TElement>(IDataAccessAdapter adapter, DynamicQuery<TElement> query)
{
return await adapter.FetchQueryAsync(query);
}
}
How do i apply this wrapper with Moq to mock the interface?
You started with an extension method and then you created your IWrap interface along with an implementation that uses the extension method. That's perfect.
Now all you need is to inject it into your class, just like IDataAccessAdapterProvider is already injected:
public class QueryHandler
{
private readonly IDataAccessAdapterProvider _dataAccessAdapterProvider;
private readonly IWrap _wrap; //I'm assuming you'll want a different name.
public QueryHandler(IDataAccessAdapterProvider provider, IWrap wrap)
{
_dataAccessAdapterProvider = provider;
_wrap = wrap;
}
(I applied a common convention there. Prefixing the field names with an underscore - _wrap - means that the field and constructor arguments have different names, so you don't need to specify this.wrap. Plus when people see that underscore elsewhere they'll know it's a field.)
Now you can mock the interface:
var mock = new Mock<IWrap>();
var returnedFromMock = new List<int> { 1, 2, 3 };
mock.Setup(x => x.FetchQueryAsync<int>(It.IsAny<IDataAccessAdapter>(), It.IsAny<DynamicQuery<int>>()))
.ReturnsAsync(returnedFromMock);
You mentioned that there is no way you can change the code. I'm not sure which part you can't change, but if you can't change QueryHandler to replace its concrete dependencies then this may just be a cautionary tale about static dependencies.
You have the source code, though. If you can't change the existing class, perhaps you can just create a new one from the existing source code. If someone asks why you duplicated an existing class, just say (tactfully) that you don't want to duplicate code - you'd rather fix the existing one so that it's testable.

Moq. Mock system class

I recieve an old project and start to refactor it for SUT purposes. I use Moq and NUnit framework. I met next class inside this project:
public ServerRunner()
{
Name = ConfigurationManager.AppSettings["ServiceName"];
WinService = new ServiceController(Name);
logger = new Logger.Logger(Name);
syncRoot = new ReaderWriterLockSlim();
timeoutMilliseconds = 10000;
}
I am new in unit test world so I need advice - how can I extract and mock System.ServiceController class? Can it be done by Moq or I should use some other Mock frameworks?
If you want to mock ServiceController I'd put it behind an interface. For example,
interface IControlServices {
// ... methods you want to implement
}
class MyServiceController {
private ServiceController _serviceController;
public MyServiceController(ServiceController servicecontroller){
_serviceController = servicecontroller;
}
// ... methods you want to implement from interface
}
Then use dependency injection (not necessarily with a DI framework) to get it into your ServerRunner class.
It looks that ServiceController is not an easily Moqable class, but you can always do the following:
Wrap the functionality you need from that class into another custom class (say ServiceControllerWrapper).
Extract the interface (IServiceControllerWrapper).
Pass an IServiceControllerWrapper instance to the constructor of ServerRunner and use that instance in the class.
Then you can test the ServerRunner class passing a Moq of the IServiceControllerWrapper interface as a parameter to the constructor.
It would look like this:
public ServerRunner(IServiceControllerWrapper controllerInstance)
{
Name = ConfigurationManager.AppSettings["ServiceName"];
WinService = controllerInstance;
logger = new Logger.Logger(Name);
syncRoot = new ReaderWriterLockSlim();
timeoutMilliseconds = 10000;
}
Hope this helps!

Is it possible to mock a local-initialized object with MOQ?

I have the following code:
public class DB
{
public virtual int GetNumbers()
{
return 42;
}
}
public interface ITestable
{
int TestMethod();
}
public class Testable : ITestable
{
public int TestMethod()
{
DB db = new DB();
return db.GetNumbers() + 20;
}
}
Now I want to use MOQ to create a mock of DB, so that every time the DB is created and initialized (Just like in the Testable.TestMethod), it will use the mocked DB instance.
For example, maybe I can setup the DB Mock so that for all DB's instance, when the GetNumbers method is called, it will return 12 instead of 42. Such that the Testable.TestMethod will return 32, instead of 62.
I want to know is it possible for MOQ to handle such kind of scenario? Actually I know that TypeMock Isolator and Microsoft Fakes Framework can achieve this. And I also don't like to go with the "Test Driven Development" approach (Which means I need to adjust my design).
No, you cannot mock that with Moq nor any other dynamic proxy based framework. You don't need TDD (which has little to do with your problem) - what you should be looking at instead is Dependency Injection (this will alter your design).
Testable version of your code would require factory and abstraction over DB object, for example:
public class Testable : ITestable
{
private readonly Func<IDb> dbFactory;
public class Testable(Func<IDb> dbFactory)
{
this.dbFactory = dbFactory;
}
public int TestMethod()
{
var db = dbFactory();
return db.GetNumbers() + 20;
}
}
With Moq, this is the most common approach to such problems. You'll have to resort to paid tools if you want to stick with your current design.

How to type cast interface to a concrete type

I am trying to mock the ManagementObjectSearcher class and have created a IManagementInfo interface, so how can i cast the interface to the ManagementObjectSearcher class?
ManagementObjectSearcher s = new ManagementObjectSearcher();
IManagementInfo info = s as IManagementInfo;
this creates me a null info object
ManagementObjectSearcher s = new ManagementObjectSearcher();
IManagementInfo info =IManagementInfo(s);
this gives me run time error (cannot typecast)
You cannot do that. Do you want to do it so that you can write unit tests? If you are trying to mock a class that you have no control of, then you have to wrap it in another class.
public class MyManagementObjectSearcherWrapper : IManagementInfo
{
public void TheMethodToMock()
{
var searcher = new ManagementObjectSearcher();
// The code you want to mock goes here
}
}
And you run your code like this:
public void YourCode(IManagementInfo info)
{
info.TheMethodToMock();
}
Then YourCode() will take either your wrapper or the mocked object. You create your mock using the IManagementInfo interface.
It looks as if you are trying to wrap a 3rd party/system object in order to aid unit testing.
Say that your starting point is
public class Dependency {
public string Foo() {
return "foo"; // machine, system, time, something else, dependent result
}
public string Bar() {
return "bar";
}
}
public class MySimpleClass {
public string MyFunc() {
return new Dependency().Foo();
}
}
[TestMethod]
public void TestSimple() {
var client = new MySimpleClass();
Assert.AreEqual("foo", client.MyFunc());
}
We are creating the Dependency inside the call because we are considering the creation cost to be less important than holding on to an instance of the Dependency. This will be dependent upon the situation. We could as easily have created a Dependency in the ctor and stored a copy which we invoked each time. Either way, we have no control over the output which makes unit testing messy.
We need to create a proxy for it.
1. Define an interface for the members that we need
Most likely, we do not need to use all of the members of the wrappee so only include in the interface those about which we care.
public interface IDependencyProxy {
string Foo();
}
2. Create a Proxy Class
We then create a proxy class wrapping the dependency and implementing interface. Again, we can create at start or on a call by call basis.
public class DependencyProxy : IDependencyProxy {
public string Foo() {
return new Dependency.Foo();
}
}
3. Define our client code in terms of the interface
We modify our client code slightly to use the IDependencyProxy interface instead of the Dependency. There are a few ways of doing this. I generally use an internal ctor which takes the dependency chained from a public ctor. (Use [InternalsVisibleTo] to allow the unit tests to see it)
public class MyRevisedClass {
private readonly IDependencyProxy dependency;
public MyRevisedClass()
: this( new DependencyProxy()) {}
internal MyRevisedClass(IDependencyProxy dependency) {
this.dependency = dependency;
}
public string MyFunc() {
return dependency.Foo();
}
}
This allows us a default behaviour for the production code (invokes the System object) and allows us to mock out the results for unit testing.
[TestMethod]
public void TestRevisedDefault() {
var client = new MyRevisedClass();
Assert.AreEqual("foo", client.MyFunc());
}
[TestMethod]
public void TestRevisedWithMockedDependency() {
var dep = new Mock<IDependencyProxy>();
dep.Setup(mk => mk.Foo()).Returns("bar");
var client = new MyRevisedClass(dep.Object);
Assert.AreEqual("bar", client.MyFunc());
}

What is the proper way to use the Ninject RhinoMocksMockingKernel to test a class that has two constructor arguments of the same type?

I am testing a class that has two dependencies on IFoo. Both instances of IFoo should be MOCK objects so that I can VerifyExpectations on each. Each instance is created and managed by the RhinoMocksMockingKernel.
I think that the mocking kernel is getting confused about which instance it should be verifying.
I also think that I may be confused about the proper way to setup RhinoMocksMockingKernel for this case.
I do know that I can use dep1.AssertWasCalled... vs. dep1.VerifyAllExpectations().
Here is the sample code.
public interface IFoo
{
void DoX();
void DoY();
}
public class SubjectUnderTest
{
private readonly IFoo dep1;
private readonly IFoo dep2;
public void DoWork()
{
dep1.DoX();
dep2.DoY();
}
public SubjectUnderTest(IFoo dep1, IFoo dep2)
{
this.dep2 = dep2;
this.dep1 = dep1;
}
}
[TestFixture]
public class Tests
{
[Test]
public void DoWork_DoesX_And_DoesY()
{
var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
var dep1 = kernel.Get<IFoo>();
var dep2 = kernel.Get<IFoo>();
// tried this binding but it doesnt seem to work
kernel.Bind<SubjectUnderTest>()
.ToSelf()
.WithConstructorArgument("dep1", dep1)
.WithConstructorArgument("dep2", dep2);
var sut = kernel.Get<SubjectUnderTest>();
dep1.Expect(it => it.DoX());
dep2.Expect(it => it.DoY());
sut.DoWork();
dep1.VerifyAllExpectations();
dep2.VerifyAllExpectations();
}
}
As ryber said, you should not really be using your IOC container in your tests that way. However, I'll still answer the question in case you have this issue in normal code. You can use the Named attribute as shown in this other stackoverflow question: How To Use Ninject Named Bindings With DependencyResolver and PropertyInjection
In that example, the Named attribute is above of the function but you can also put it right next to your arguments to specify which one should be used. E.g.
public void SubjectUnderTest([Named("Alpha")] IFoo alpha, [Named("Beta")]) {
...
}
And the bindings should be registered as such described in this post: How To Use Ninject Named Bindings With DependencyResolver and PropertyInjection
You can also use a the ToMethod binding to just manually create your object.
So I found a way to verify the expections on dep1 and dep2, but I was not able to use the AutoMockingKernel to manage and create dep1 and dep1.
Here is the code that I came up with.
It's pretty lame answer. It seems like I should be able to use the mocking kernel to Get two seperate instances of IFoo...
Here is my current code... lameo...
[TestFixture]
public class Tests
{
[Test]
public void DoWork_DoesX_And_DoesY()
{
var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
var dep1 = MockRepository.GenerateMock<IFoo>();
var dep2 = MockRepository.GenerateMock<IFoo>();
kernel.Bind<IFoo>().ToMethod((ctx) => dep1).When((ctx) => ctx.Target.Name.StartsWith("dep1"));
kernel.Bind<IFoo>().ToMethod((ctx) => dep2).When((ctx) => ctx.Target.Name.StartsWith("dep2"));
var sut = kernel.Get<SubjectUnderTest>();
dep1.Expect(it => it.DoX());
dep2.Expect(it => it.DoY());
sut.DoWork();
dep1.VerifyAllExpectations();
dep2.VerifyAllExpectations();
}
}

Categories