Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Lets say we have a Service with other servcies on DI. The method under test does somehting with the input data, does some validations, calls a couple of these injected services (can get data only or modify data and then return something) and then returns something.
Given this scenario, I need to write many cases testing all possible behaviors, like validations exceptions, not found exceptions, business exceptions, normal flow, etc...
The problem is that I need to mock all the methods on an injected service for the setup. This could grow fast.
What's the best approach for fixtures and setups (mocking dependencies) in this large/complex method? Is there a pattern that solves this?
For data mocking I use builder pattern wich simplifies the task very well.
You should try create independent classes, which you could test without introducing too many dependencies, but in some point there will be a class which uses other components(for example ViewModel). In such cases I use:
https://github.com/AutoFixture/AutoFixture
It helps in creation system/class under test and helps with injecting dependencies. You can use it with NSubstitute but not only with it.
Using AutoFixture you can create mock classes which you will examine, but rest dependencies which will be not needed AutoFixture will auto-generate for you, so extending a constructor will not lead to modifying bunch of unit tests.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have never used a ioc-Container but from what I have read, the objects suffixed with "Container" seem to me a factory that reads from configuration/context, does its magic and returns an object of concrete type according to the read configuration/context.
What key aspects am I missing?
Using containers seems to add complexity (which is time consuming for development, refactoring and configuration), where to use and which are the key benefits?
Both IoC containers and factories build other objects, but that's where the similarities end.
A factory is an object which knows how to build other objects. It encapsulates extra logic, perhaps configuration time information etc. It can build several of a related type of objects, such as from a hierarchy of objects. But the number of objects it can build is part of the structure of the factory. So you might have a SqlConnectionFactory or a RequestHandlerFactory, which know what sort of SqlConnections or RequestHandlers to build, but if you want to build InputValidators you're going to need to make a new factory.
An IoC container is a tool used to help with the inversion of control pattern. But it's not strictly needed. IoC makes you be explicit in what dependencies your objects have, and makes you provide those dependencies when the object is created/initialized. When done right, this helps with separation of concerns, decoupling between components, unit testing etc. and generally makes the resulting code "better". But because manually wiring up object graphs is a hassle, a number of frameworks for doing this automatically, either from external configuration or from code annotations have appeared. These are called IoC containers. The way they initialize objects is much more generic than a factory. You can ask it to build any type of object, and as long as it knows something about those objects (the signature of the constructor, in the simplest case), it can build them.
It's more usual to see an IoC container use a factory, than the other way around. In much of the code I've seen, the need for factories for all but the most complex objects is greatly alleviated though.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I mock a service that I do not have control of (an external companies service to which I have access but do not want to hit when running my unit tests).
I am writing my consumer in C# .NET 4.6. My intended aim is to be able to test the inner workings of my consumer (and then the library code that consumes that) without actually hitting the remote service. Unfortunately the remote service is rather complicated and has a large number of calls and types of its own.
Any assistance or pointers would be greatly appreciated.
Edit: After an immediate down vote with no comment; please let me add: I have goggled this but unfortunately did not get answers that helped me. Perhaps just poor search terms.
Edit 2: The remote service is asmx. My consumer is a .net 4.6 library that will act as the control library for any consuming user interface (be it wpf, winform, mvc, etc).
You can abstract the external service functionality into an interface (IExternalService), and then create another implementation for it (besides the original one), a mock one: MockExternalService. This one could be as simple as just return some dummy data, or can also have some logic inside (return different response depending on a certain input in method params, for example).
You then need to wire all this up so that through a certain mechanism (custom header/web.config setting/db setting, for example) your consumer can swap between the 2 different service implementations (this somewhat implies that you're using Dependency Injection).
Right click on the imported Service Reference class, choose "Extract Interface" and you have the beginnings of your mock. Change all your existing code that references the concrete service reference class to referencing the new interface, then where you create a new instance of the concrete class, replace that code with a factory using your favourite IOC framework (or just write the factory yourself).
Then create a "TestServiceEndpoint" class implementing the extracted interface and start writing your mock responses.
Alternatively use the Visual Studio Fakes capability to create a Fake implementation and write tests with that. This is only really suitable for a unit test framework environment though, so if you are trying to stub out the endpoint so you can test the rest of your application, the first approach is the best.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am working for a consulting company that develops a lot of Add-Ons for SAP Business One using .NET. I want to introduce TDD (or at least some good unit testing practices) to the company to increase code quality. Here's the problem.
SAP provides a COM object (called Company) that lets you interact with the data in SAP. Company is an interface, so it can be mocked, but the amount of Mocking that would have to be done to get a single test to run is huge! I've tried it out with a few tests, and although they work, I really had to have a good understanding of the internals of the unit that I was testing, in order to create tests that passed. I feel that this very much defeats the purpose of the unit tests (I'm testing the internals as opposed to the interface).
Currently, through the use of dependency injection, I've created a Mock Company object that returns some Mock Documents that will sometimes return Mock values based on different circumstances, just to get the tests to run. Is there a better way? Has anyone been able to effectively unit test code that heavily depends on some external library? Especially when the results of the tests should be some change to that mocked object? (Say, when the add-on runs, the Mock Company object's SaveDocument function should be called with this Mock document).
I know this may be a strange question, but the fact of the matter is that in order to get these unit tests to run well, I feel like the only option to me is to create a really...reaally large mock that handles multiple Mock Documents, knows when to give the documents at the right time, and a lot of other things. It'd be essentially mocking out all of SAP. I don't know if there's some other best practice that others do in these cases.
Thanks in advance!
EDIT: Carl Manaster:
You're probably right. I think the problem is that most of the existing code base is very procedural. A lot of Windows services with a Run() method. I can definitely see how, if the project was structured a bit better, tests could be made with a lot more ease.
But let's say that the company can't invest in refactoring all of these existing projects. Should I just abandon the idea of unit testing these things?
If your methods are short enough, you should be able to mock only the interactions with one entity (Company), without interacting with the entities it returns. What you need is for your method to call (let's say) company.getDocument(). If your method under test has further interactions with the returned document at that point, split out that code, so that you can test that code's interactions with a (mocked) Document, without worrying about the Company in that test. It sounds as though your methods are currently much too long and involved for this kind of approach, but if you whittle away at them to the point where testing one method simply verifies that company.getDocument was called, you will find it much easier to test, much easier to work with, and ultimately much easier to understand.
Update
To your question of whether you should abandon the idea of unit testing: Do you want it to work? Do you have changes to make to the code? If the answers are (as I would assume) affirmative, then you should probably persevere. You don't have to test everything - but test what you're changing. You don't have to refactor everything - but refactor what you're working on so it's easier to test and easier to change. That "whittling away" that I mentioned: do that in service of solving the problems you have at the moment with your code base; over time you will find the code that most needed the tests has been tested - and it's a lot easier to work with because it's well tested and better factored.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I know that there are many IoC frameworks in .net ( They are: Ninject, Unity, Castle Windsor , Structure Map ) They also used to same goal - resolving dependencies. But i don't understand in which cases should be used certain framework! they are almost similar. Who can simply explain the main differences?
It depends on your needs. Some containers are very mature or have a big community. Others are feature rich or very fast. It all depends on what you need, but the problem is that you only know this when you already did one or two projects using DI and DI containers. And still, when you're architecture changes the requirements for your container will change.
So whatever container you pick, be prepared to change your container. This means, stick to the Dependency Injection pattern and prevent yourself from letting application code have a direct dependency on the container (a pattern which is called Service Locator).
Each and every one has a fatal flaw.
On a more serious note they surely do essentially the same thing, but differ in implementation details, conventions, performance, auxiliary features and suggested usecases.
I don't think that you should really sweat picking the IoC container. Stick to one you're used to and continue with your core functionality.
DI/IOC or whatever you want to call it is a means to an end - not the end in itself. Find one you like and that does everything you need and go with it (until you're told to use something else).
I rolled my own based on StructureMap and probably learned more doing that than actually using any of the others.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My class has like 30-40 properties, and I really want to unit test.
But I have to create a moq instance (many of them, with different combinations etc).
Is there an easy way? This is real work!
My class can't be refactored, "trust me" (hehe, no really it can't, they are just properties of the object that are very tightly coupled).
Sounds like you need to do some major refactoring. I would start by taking a good look at the single responsibility principle, and making classes that will only have 1 reason to change. Once you break out functionality into separate classes that deal with only 1 responsibility, you can start writing tests for those classes, and they shouldn't take a page-full of mock objects.
This is the advantage of test-driven development -- you immediately run into the problems caused by huge classes, and are driven to avoid them if you want to be able to write tests.
Personally, I don't think you need to try every combination to test your class.
You mention lots about properties, but little about behavior. Shouldn't the tests be about behavior more than state?
There could well be situations where, due to the nature of the class, there are a lot of legitimate properties. I know, I've been there and done that. When examining that class, it is important to determine that each property really does belong in the one class, and not elsewhere. Single Responsibility Principle comes in play here.
Unfortunately, to break any tight coupling, it will take some time and effort to refactor. Just suck it up and get 'er done!