Using ASP.NET core Dependency injection to inject multiple implementations of an Interface.
This is how my code looks:
public factory(IEnumerable<ISomeInterface> interfaceImplList){}
public class Impl1:ISomeInterface(){}
public class Impl2:ISomeInterface(){}
public class Impl3:ISomeInterface(){}
public class Impl4:ISomeInterface(){}
All the above implementations are injected into the factory and factory will return some implementation based on some configs (Not related to the question)
Now I want to mock this factory using moq. Is there a way to do that, or should I create all the mocked implementations of above classes and them put them in a IEnumerable and pass?
Also another question, is it even a good unit testing practice to create a factory to return mocked instance or should I directly unit test the individual implementations?
Related
I am doing unit testing using NUnit and Moq framework. When I try to mock the IRepository using mockRepo.Setup(x=>x.GetStr(It.IsAny)()).Returns(str) then the method which is to be tested gets overridden inside Repository class and the build fails. But instead mocking the IRepository if I mock the Repository making the method which is to be tested as virtual then the data is getting mocked and the test runs.
Any kind of mocking relies on members to be overridable. Your mocking-framework will create some class that either implements your interface or overrides your class. So what the framework creates is similar to the following:
class WeirdClassName : IRepository
{
string GetString(object o) => "SomeString";
}
or if your member would be a class-member this:
class WeirdClassName : Repository
{
string override GetString(object o) => "SomeString";
}
Interface-members are implictely overridable, as they literally do not provide any own logic. You can allways provide your own implementation for it. Class-members are only overridable, if they are virtual.
In your case there seems to be some difference in the test depending on if you mock the interface or the class. That probably indicates your test depends on some internals of the class - e.g. some initialization on the repo. You should either mock that also, or decouple your test from that dependency.
I'm new to the moq framework in .net.
From my research online, it seems like there are 2 ways to make use of this framework. Either mock the interface or mock a concrete class. Seems like when mocking concrete class, only virtual method can be mocked. In my case, I just want to mock a couple method of a class which implements an interface.
For example, if we have the following:
public interface Ifoo
{
int Bar();
}
public class Foo : Ifoo
{
public virtual int Bar()
{
return 0;
}
}
public class Client
{
public Client(Ifoo foo)
{
var temp = foo.Bar();
}
}
Now if I need to unit test Client, I need to pass a mocked Ifoo object in the ctor. In this case, should I do:
var mock = new Mock<Ifoo>();
or
var mock = new Mock<Foo>();
Does it make a difference in my case? What's the pros and cons of mocking interface vs mocking class? To me, mocking interface is always a better solution since mocking a class can only give the mock of the virtual method.
Here are some points to consider:
Your client consumes IFoo, so that's what you should mock.
If your client consumes a concrete class, you should think about refactoring your client to consume the interface or abstract class instead to comply with SOLID principles.
If your client consumes a mock of Foo during your test instead of the interface and it relies on some of the non-mocked behavior in that test, you're not really writing a unit test since you're testing the behavior of more than one unit.
If your client doesn't consume any non-mocked behavior during the test then you might as well just pass a mock of the interface anyway.
tldr: Classes should consume interfaces or abstract classes rather than concrete classes. Tests should mock interfaces or abstract classes rather than concrete classes.
I am trying to unit test a class that uses factory injection. I have a class that instantiates two copies of the same object (with different config) to control hardware. I'm trying to test the behaviour of the classes while simulating the hardware calls.
I've injected a set of factory delegates into the constructors so that the class can instantiate the hardware classes as required. However I just can't work out how to control or create factory methods within the Autofac.Extras.Moq package. It seems that this functionality isn't supported in the package.
I'm looking for an equivalent call to :
mock.Provide<IHWController>(//created by factory delegate)
I want to create a specific mock object with behaviour, based on the parameters used to instantiate the HWcontroller. Is what I'm trying to do even possible?
class SystemUnderTest
{
SystemUnderTest(Ia a, Ib b, Ic c,
/** 15 other things **/
Func<Func<Uri, IHwController>, HwType, IHwManager> HwManagerFactory,
Func<Uri, IHwController> HwControllerFactory)
{
}
}
class HwManager()
{
public Func<HwType, Func<Uri, HwController>, HwManager> Factory;
public HwManager(HwType type, Func<Uri, HwController> ControlFactory)
{
//Constructor
}
}
The code I'm unit testing creates Managers of controllers. The controller is the hardware layer, but I'm testing complex (coupled) behaviour inside the manager. Therefore, I'm trying to work out how to mock the Func<Uri, HwController> ControlFactory so that it returns my setup mock objects so that I can probe the behaviour of the manager.
My system under test creates a concrete instantiation of the HWManager. I realise in a perfect scenario I would test the HwManager and SUT separately, but I'm specifically testing the integration of the two components.
I'd like to configure the autofac to control the delegate factory. If this isn't possible, then I can manually setup the SUT, but then I don't get any value from the autofac helper.
I usually just create a Func that returns my mocked instance e.g.
var controller = mock.Provide<IHWController>();
var manager = new HwManager(something, (uri) => controller);
If the factory is expressing "given a Uri I will provide a controller", the lamda in my example above satisfies that statement.
As an aside, you should express your factories using interfaces, not concrete classes. It makes it a lot harder to unit test when the factories are producing concrete classes instead of interfaces (which can always be mocked) e.g.
// IHwController is the product of the factory instead of HwController
public HwManager(HwType type, Func<Uri, IHwController> ControlFactory)
If anyone gets stuck on this in the future, the key is to create a func that matches the constructor func, customised to provide the appropriate mocks on each invokation (e.g. via an internal counter).
You can then use the mock.Provide() syntax, providing a func that matches the constructor func with your created func above. This will then be invoked correctly allowing you to control the mocks appropriately.
I am working on .NET 4.0 using C# in Windows 7.
I want to test the communication between some methods using mock. The only problem is that I want to do it without implementing an interface. Is that possible?
I just read a lot of topics and some tutorials about mock objects, but all of them used to mock interfaces, and not the classes. I tried to use Rhino and Moq frameworks.
Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method.
If you use new Mock<Type> and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects
Most mocking frameworks (Moq and RhinoMocks included) generate proxy classes as a substitute for your mocked class, and override the virtual methods with behavior that you define. Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.
Why the aversion to creating interfaces in your code?
With MoQ, you can mock concrete classes:
var mocked = new Mock<MyConcreteClass>();
but this allows you to override virtual code (methods and properties).
I think it's better to create an interface for that class. And create a unit test using interface.
If it you don't have access to that class, you can create an adapter for that class.
For example:
public class RealClass
{
int DoSomething(string input)
{
// real implementation here
}
}
public interface IRealClassAdapter
{
int DoSomething(string input);
}
public class RealClassAdapter : IRealClassAdapter
{
readonly RealClass _realClass;
public RealClassAdapter() => _realClass = new RealClass();
int DoSomething(string input) => _realClass.DoSomething(input);
}
This way, you can easily create mock for your class using IRealClassAdapter.
Hope it works.
If you cannot change the class under test, then the only option I can suggest is using MS Fakes https://msdn.microsoft.com/en-us/library/hh549175.aspx.
However, MS Fakes works only in a few editions of Visual Studio.
The standard mocking frameworks are creating proxy classes. This is the reason why they are technically limited to interfaces and virtual methods.
If you want to mock 'normal' methods as well, you need a tool that works with instrumentation instead of proxy generation. E.g. MS Moles and Typemock can do that. But the former has a horrible 'API', and the latter is commercial.
If worse comes to worse, you can create an interface and adapter pair.
You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.
The adapter implements the interface, so the mock can also implement the interface.
It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.
It is a bit old question but nevertheless. There are powerful mocking frameworks these days that are capable of mocking concrete classes like JustMock and Typemock.
I faced something like that in one of the old and legacy projects that i worked in that not contains any interfaces or best practice and also it's too hard to enforce them build things again or refactoring the code due to the maturity of the project business, So in my UnitTest project i used to create a Wrapper over the classes that I want to mock and that wrapper implement interface which contains all my needed methods that I want to setup and work with, Now I can mock the wrapper instead of the real class.
For Example:
Service you want to test which not contains virtual methods or implement interface
public class ServiceA{
public void A(){}
public String B(){}
}
Wrapper to moq
public class ServiceAWrapper : IServiceAWrapper{
public void A(){}
public String B(){}
}
The Wrapper Interface
public interface IServiceAWrapper{
void A();
String B();
}
In the unit test you can now mock the wrapper:
public void A_Run_ChangeStateOfX()
{
var moq = new Mock<IServiceAWrapper>();
moq.Setup(...);
}
This might be not the best practice, but if your project rules force you in this way, do it. Also Put all your Wrappers inside your Unit Test project or Helper project specified only for the unit tests in order to not overload the project with unneeded wrappers or adaptors.
Update:
This answer from more than a year but in this year i faced a lot of similar scenarios with different solutions.
For example it's so easy to use Microsoft Fake Framework to create mocks, fakes and stubs and even test private and protected methods without any interfaces.
You can read: https://learn.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017
I've a WCF Service which is hosted inside MVC Application. Service interacts with several Repository (I've Code First design) to do its job. Currently I create an instance of all Repository classes inside each Service method, I think it is bad and my Service is totally coupled to Repository classes. I want to know how should I implement a nice and clean DI for WCF Service.
Thanks in Advance.
One approach you can take is to inject a repository factory in your service class and then call/get your repository from the factory.
Repository Factory:
public interface IRepositoryFactory
{
IRepositoryOne GetRepositoryOne();
IRepositoryTwo GetRepositoryTwo();
}
public class RepositoryFactory: IRepositoryFactory
{
public DataAccess.RepositoryInterfaces.IRepositoryOne GetRepositoryOne()
{
return new RepositoryOne();
}
public DataAccess.RepositoryInterfaces.IRepositoryTwo GetRepositoryTwo()
{
return new RepositoryTwo();
}
}
Service Class:
public ServiceClass: IService
{
private readonly IRepositoryFactory _repositoryFactory;
public ServiceClass(IRepositoryFactory factory)
{
_repositoryFactory = factory;
}
public IList<YourItems> GetYourItems()
{
var repository = _repositoryFactory.GetRepositoryOne();
return repository.GetItems(....);
}
}
With this approach, you'll need to register and resolve only your repository factory, not all the individual repositories. This is sort of hybrid approach, but I think it's very clean and easy to understand. Of course, you can always not use a factory and resolve your repositories in every call. I can show a sample of that too, if you'd like.
I would recommend using the Dependency Inversion Principle: Have your repositories implement a specific interface, then have your service classes take in an object (or objects) of that interface (or interfaces). Do not have it directly reference the concrete class. Then, all you'd need to do on your service class is call a method that's exposed by the interface to bring up any/all of the information that you want.
Doing so will de-couple the code from each other, since they'd both be relying on abstractions, and you'll still get the wonderful functionality that you're requesting.
Here's how you could go about doing it: Let's say your WCF service class needs RepositoryA, which implements IRepositoryA. What you would do is have a field (usually private) of type IRepositoryA on it. Then create a constructor in the service that takes in an object of type IRepositoryA, and then sets the field variable with that object being passed in. Something like what's found on this site:
For more information on the Dependency Inversion Principle, just read what Uncle Bob has to say.