简体   繁体   中英

Integration Test Using Autofac and Moq

Is it a good idea to use Autofac and moq to develop integration test? Most of examples and documentation I found online, focus on using the two on Unit test. Any good example for Integration test? And by integration test I mean some approach like button up, top down, or sandwich approaches.

I recommend you define what you mean by integration test, because the term has no one accepted definition. I will assume you mean testing an entire application in isolation, ie testing multiple (maybe hundreds) of classes together, but without interacting with external systems (eg databases, http services).

It's a great idea to introduce some sort of dependency injection or inversion of control to your project. Whether you use Autofac or some other solution, the benefits in integration tests are the same - dependency injection allows you to replace the bits of your system that communicate with the outside world, eg your DAO, with a mock or stub version that operates in memory. For example, in production you would use a DAO backed by an external MSSQL database perhaps, but in integration tests you would use a stub DAO backed by an in memory Dictionary or HashMap perhaps.

As for Moq, I would not recommend using Moq for integration tests. Mocking is great for Unit Tests because Unit Tests test very small areas with the system and the interaction with the mock object is often simple (if not, then maybe you should refactor your Unit Test!). With integration tests, however, you are testing your entire system and it's possible that there will be many, many interactions with the object you are trying to mock. Furthermore, as the system changes, the interaction with the mock might change, even if the results stay the same. It can become very difficult and tedious to set up and maintain a mock for an integration test because of this because often you will have to set up many, many method calls.

Furthermore, integration tests may be multi-threaded and things might not always happen in the same order. Again, difficult to mock!

A better approach for integration tests is to actually implement an in memory version of your object. It should behave as closely as possible to the real thing. Likely you will have to add additional methods to this in memory implementation to do things like set up initial state (in the DAO example, set up some test data) or inspect output. You will find this much more flexible in the long run as your integration test base grows.

To be clear, I think Moq is very useful for Unit Tests, just not Integration Tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM