How to mock Autofac IComponentContext.Resolve<IRepository> - unit-testing

I am looking how to mock autofac Resolve method. I am using NUnit and NSubstitute for unit tests.
I have a Business method which calls Repository method, and inside business method, i am using
_container.Resolve< IRepository>().GetData()==> here _container is IComponentContext.
Instead of calling real db, i want to mock repository method, but i am not able to do that, every time this line tries to call real db.
In my unit tests, I am trying to mock like this....
private IRepository _Repository;
_repository = Substitute.For< IRepository>();
_repository.GetData().Returns("abc");

Don't try to mock dependency injection. Instead of mocking DI, register your mock with Autofac.
This may mean that you need to modify your code so it allows you to add registrations to the container in a test scenario. In ASP.NET Core they have a notion of ConfigureTestServices for example that allows you to put registrations in a method that only get run in a test scenario.
Another way to do it is to use a custom Startup class where all the methods are virtual so you can override ConfigureServices or ConfigureContainer to register test overrides.
Unfortunately, exactly how you do this is so very application specific that there's not "one way to do it" or a "best practice." You're going to have to do some searching and looking at your own app to figure it out.
However, the takeaway here is: Don't try to mock DI. Use real DI with mocks inside the container.

Related

Does django testing have a breakDown() similar to setUp() that is ran after all tests complete?

I am running some tests in django but they depend on a response from an outside service. For instance,
I might create a customer and wish to acknowledge it has been created in the outside service.
Once I am done with testing I want to remove any test customers from the outside service.
Ideally, there would be a method similar to setUp() that runs after all tests have completed.
Does anything like this exist?
You can make use of either unittest.TestCase.tearDown or unittest.TestCase.tearDownClass
tearDown(...) is the method gets called immediately after the test method has been called and the result recorded.
but, the tearDownClass(...) is gets called after tests in an individual class have run. That is, once per test class.
IMO, using tearDownClass(...) method is more appropriate since you may not need to check/acknoledge the external service after search test cases of the same class
So Django's testing framework uses a Python standard library module, unittest. This is where the setUp() method comes from.
This library contains another method tearDown() that is called immediately after the tests are run. More info can be found here

Spring webflux unit test method which returns Mono/Flux

I am using spring webflux in my project. My controller class calls service class methods which returns Mono or Flux.
I am trying to write unit tests for my service class. I am not sure how to write unit tests for a method which returns Mono/Flux. Most of the articles I checked suggested me to use WebclientTest. But the point is, I am testing my service class here. I have used WebclientTest when I tested my web layer(controller class) by mocking service class methods.
Now I want to write unit tests for my service class methods(by mocking database class)
Any ideas on how to achieve this? Should I use call the service class method from test and call block() or is there a better way?
You can use StepVerifier provided by Project Reactor for testing purposes.
Although, for simple scenarios (for example when you only have a Mono) a block call will do just fine.
StepVerifier might come in handy when you...
have a Flux and want to assert multiple items/events flowing through the pipeline
deal with time
test Reactor context

Should I mock all the direct dependencies of a class in unit tests?

Let's say that we have a class Controller that depends on a class Service, and the Service class depends on a class Repository. Only Repository communicates with an external system (say DB) and I know it should be mocked when unit testing is executed.
My question: For unit tests, should I mock the Service class when Controller class is tested even though the Service class doesn't depend on any external systems directly? and Why?
It depends on the kind of test you are writing: integration test or unit test.
I assume you want to write a unit test in this case. The purpose of a unit test is to solely test the business logic of your class so every other dependency should be mocked.
In this case you will mock the Service class. Doing so also allows you to prepare for testing certain scenarios based on the input you are passing to a certain method of Service. Imagine you have a Person findPerson(Long personID)-method in your Service. When testing your Controller you are not interested in doing everything that's necessary for having Service actually return the right output. For a certain test scenario for your Controller you just want it to return a Person whereas for a different test scenario you don't want it to return anything. Mocking makes this very easy.
Also note that if you mock your Service you don't have to mock Repository since your Service is already a mock.
TLDR; When writing a unit test for a certain class, just mock every other dependency to be able to manipulate the output of method invocations made to these dependencies.
Yes, mock Services when testing controllers. Unit tests help to identify the location of a regression. So a Test for a Service code should only fail if the service code has changed, not if the controller code has changed. That way, when the service test fails, you know for sure that the root cause lies in a change to Service.
Also, usually it is much easier to mock the service than to mock all repositories invoked by the service just to test the controller. So it makes your tests easier to maintain.
But in general, you may keep certain util classes unmocked, as you loose more than you gain by mocking those. Also see:
https://softwareengineering.stackexchange.com/questions/148049/how-to-deal-with-static-utility-classes-when-designing-for-testability
As with all engineering questions, TDD is no different. The answer always is, "it depends". There's always trade offs.
In the case of TDD, you develop the test through behavioral expectations first. In my experiences, a behavioral expectation is a unit.
An example, say you want to get all users that start with the last name 'A', and they are active in the system. So you would write a test to create a controller action to get active users that start with 'A' public ActionResult GetAllActiveUsersThatStartWithA().
In the end, I might have something like this:
public ActionResultGetAllActiveUsersThatStartWithA()
{
var users = _repository.GetAllUsers();
var activeUsersThatStartWithA = users.Where(u => u.IsActive && u.Name.StartsWith('A');
return View(activeUsersThatStartWithA);
}
This to me is a unit. I can then now refactor (change me implementation without changing behavior by adding a service class with the method below)
public IEnumerable<User> GetActiveUsersThatStartWithLetter(char startWith)
{
var users = _repository.GetAllUsers();
var activeUsersThatStartWithA = users.Where(u => u.IsActive && u.Name.StartsWith(startsWith);
}
And my new implementation of the controller becomes
public ActionResultGetAllActiveUsersThatStartWithA()
{
return View(_service.GetActiveUsersThatStartWithLetter('A');
}
This is obviously a very contrived example, but it gives an idea of my point. The main benefit of doing it this way is that my tests aren't tied to any implementations details except the repository. Whereas, if I mocked out the service in my tests, I am now tied to that implementation. If for whatever reason that service layer is removed, all my tests break. I would find it more likely that the service layer is more volatile to change than the repository layer.
The other thing to think about is if I do mock out service in my controller class, I could run into a scenario where all my tests are working properly, but the only way I find out the system is broken is through an integration test (meaning that out of process, or assembly components interact with each other), or through production issues.
If for instance I change the implementation of the service class to below:
public IEnumerable<User> GetActiveUsersThatStartWithLetter(char startsWith)
{
throw new Exception();
}
Again, this is a very contrived example, but the point is still relevant. I would not catch this with my controller tests, hence it looks like the system is behaving properly with my passing "unit tests", but in reality the system is not working at all.
The downside with my approach is that the tests could become very cumbersome to setup. So the tradeoff is balancing out test complexity with abstraction/mockable implementations.
Key thing to keep in mind is that TDD gives the benefit of catching regressions, but it's main benefit to is to help design a system. In other words, don't let the design dictate the tests you write. Let the tests dictate the functionality of the system first, then worry about the design through refactoring.

creating dummy CreateShell method While Unit Testing

I want to Unit Test the view model and for that I am Inheriting Mefbootstraper class so Please suggest the method to override the CreateShell method inside Bootstrapper which returns dummy dependency object.
Based on your last comment, you could avoid creating a Shell and the entire Bootstrapper. So, instead of calling Bootstrapper's run() method, you can create mocks for RegionManager, Comnposition Container and ResourceManager in order to pass them through ViewModel's constructor.
This would not be an issue as you would load these mock instances with the minimum information needed for the test.
Furthermore, real Bootstrapper would not be needed because its functionalities would not be targeted for testing.
I hope this helps, Regards.

How to unit test a fake implementation of a repository inside a service class?

I have an object which hold a message in many language this is called a LookupString in my project.
I have also a repository for this entity which is LookupTableRepository which is implemented from ILookupTableRepository.
I have a service class which is called LookupTableProvider.. this is simply to call out the repository. It only got one method which is GetEntry(string id, cultureinfo culture) which enable to get a message in the specified culture i want.
Now i want to unit test the LookupTableProvider which hold a repository.. but i wish to use a fake repository for this purpose since a moq won't help me much there since i only want to test the implementation of the provider.
What is the best way to make the unit test provider me an implementation of the fake repository if i use Ninject ? How i can call ninject to give me an instance of this fake repository ?
You shouldn't use an IoC Container for unit testing your classes. Simply new up your Provider and pass all mocks to the constructor.