简体   繁体   中英

Mocks for service using spring.net for IoC

I'm in the process of creating unit tests for an existing serie of classes that use spring.net IApplicationContext to resolve types and I want to mock the dependencies resolved by spring.net.

I'm having problems getting spring.net to use my mocked objects, basically getting ContextRegistry.GetContext() to return them in the actual application. The best solution I've found so far is something similar to this , but is not very clean to manage in the actual unit test code, or defining my own IApplicationContext on the fly and register it in the registry which has the same problem.

My question is whether I'm missing some framework that ties these things together or some pattern I can use that would allow me to define things easily.

Your classes are using IApplicationContext as a service locator. Many consider "Service Locator" an anti-pattern . I suggest you form your own opinion on this; if you agree that it is an anti-pattern, then you can take this opportunity to factor out the dependency on IApplicationContext and replace them by explicit dependencies on the objects your class needs.

If you (have to) stick to the current approach, then I'm afraid it's really difficult to get a clean solution. In your situation, I'd configure my containers specifically for testing (perhaps including mocks like described in your linked blog post) and use Spring.net unit test support for easy wiring of my test objects. But I'd feel really uncomfortable - like you ...

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