0

I have these projects/DLLs:

  • mylib project - the project with logic I'm testing
  • mylib_test project - the nunit test project testing mylib
  • otherlib.dll - a 3rd party DLL that mylib uses
  • otherlib_mock.dll - a mock of otherlib.dll that I want to use when testing. It contains all the types that are in otherlib.dll with the same interfaces, except that it always returns mock data instead of actually doing the work that otherlib.dll does.

I want that mylib will use otherlib.dll in regular operation but when unit tests are run from mylib_test - otherlib_mock.dll will be used by mylib.

Currently, all the types are in the same namespace as otherlib.dll so if I modify mylib to reference otherlib_mock.dll instead of otherlib.dll - everything works with the mock types. Can somehow do this automatically for testing and not for regular operation?

Option 2 is: I have the code of otherlib_mock.dll. I could change its namespace to be different than otherlib.dll and then I could reference them both in mylib. Now, I toggle between the mocked and non-mocked behavior by switching between the namespaces. Can I put the using lines in #if and #else so that I use the otherlib.dll namespace in regular operation and the otherlib_mock.dll namespace when running tests?

ytoledano
  • 3,003
  • 2
  • 24
  • 39

1 Answers1

0

This is a good candidate to be solved through dependency injection. You should reference both dlls in different namepspaces, and then in your test library, inject the test library, and in production code, inject the real one.

Asif Shiraz
  • 864
  • 1
  • 12
  • 27
  • I know how to inject code, how do I inject a library? – ytoledano May 24 '16 at 20:35
  • Ideally, the calls to this library should have been written against a contract, so that injection would switch between two referenced libraries. But if you do not want to change the code, and then I guess dynamically loading the assembly should work. – Asif Shiraz May 24 '16 at 20:39
  • 1
    Alternatively, this question already explains a similar situation. Instead of architecture, you can define custom properties in your projects. http://stackoverflow.com/questions/3832552/conditionally-use-32-64-bit-reference-when-building-in-visual-studio – Asif Shiraz May 24 '16 at 20:43
  • I was able to achieve what I wanted by adding a solution configuration and a project configuration to `mylib` called Test. I now need to use them when I compile `mylib_test` in order for `mylib` to include `otherlib_mock`. It's not 100% elegant but it gets the job done. Thanks – ytoledano May 24 '16 at 21:41