Simplified testing for design considerations when using dependency injection

We spend several months in a project with green fields to remake the logical and business levels of our product. Using MEF (dependency injection), we have achieved a high level of code coverage, and I believe that we have a pretty solid product. As we work on more complex logic, the unit test has become increasingly difficult for me.

We use the CompositionContainer to query the types required by these complex algorithms. My unit tests are sometimes difficult to complete due to the lengthy installation process of the mock object that needs to take place, in order to be able to verify certain circumstances. My unit tests often take longer to write than the code I'm trying to test.

I understand that this is not only a problem with dependency injection, but with the design as a whole. Is the method design poor or lack of guilt for my overly complex tests? I tried base class tests, creating commonly used breadboard objects and ensuring that I use the container as much as possible to alleviate this problem, but my tests always end up being quite complicated and difficult to debug. What are some tips you saw to make these tests concise, readable, and effective?

+1
source share
2 answers

My subjective point of view:

  • MEF looks like a really nice plugin infrastructure; it is not intended for a full-fledged DI structure. If you don't need replaceable components, check out the full DI / IoC container frames . Unity is an alternative to Microsoft.
  • Make sure that you are not running the anti service template>. Use the constructor by inserting interfaces when possible. See this great post by Mark Semann and this Jimmy Bogard . Your expression that you "use the container as much as possible" is a concern - several classes should know something about the container.
  • Get a really good fake / insulating environment and learn how to use it. I love Moq . Try to check the state in the system under test, and not check the behavior on the layout when possible.
  • Read the Art of Testing Devices . Read other books and articles on unit testing. Practice TDD . Keep learning.
  • Read Clear code and make sure your classes follow SOLID (especially the single responsibility principle ). Long-term layout setup - the smell of code; your classes are probably doing too much. High code coverage is good, but cyclic complexity may be a better indicator.
  • Don't worry about your unit tests taking longer than production code. However, process your tests, such as production code, and remove duplication when you can maintain readability and maintainability.
+7
source

Here are some good links about DI and good design practice (in terms of writing testable code) that you can check out (google tech conversations):

I found them very useful with lots of good design test tips.

0
source

All Articles