How to use Moq in multi-

51 views
Skip to first unread message

妈豆豆

unread,
Apr 18, 2014, 5:16:50 PM4/18/14
to moq...@googlegroups.com

I am new to Moq. I have question about how to apply Moq in Multi-layer application. For example, I have application which include a Dclass to access database, a business Bclass1 to do something with the data from data access class, another business Bclass2 to do something with class1's operation and etc.  If I want to test a method in Bclass2 and want to use Moq to mock the database, should I expose the DClass's interface to Bclass2?
Or should we make Bclass1 to implement an interface, then make Mock Bclass's interface to test Bclass2?
Could you please provide with best practice of Moq in multi-layer application?

Thank you!


Zelalem

unread,
Apr 22, 2014, 5:24:25 PM4/22/14
to moq...@googlegroups.com
Hello there,
Use Moq to control dependencies and do unit level testing. In your case, it seems like BClass2 depends on BClass1 and not on DClass. Yes there seems to be an indirect dependency on DClass too but as far as BClass2, it doesn't really care about that. Now, assuming you have an interface or abstract class for BClass1(which btw, you could use concrete types too), you can declare a private field of this interface/abstract class within BClass2, and have BClass2's constructor accept this interface/abstract class as a parameter and set this field. This is just one way of injecting dependency(constructor injection)-you could also use property injection or other methods. But they will all work fine as long as BClass2 depend on higher abstractions or is not tightly coupled with concrete type of BClass1. But then this will require concrete objects to be resolved and injected at run time-probably through some sort of IOC container. Once you have that in place, you can now create a mocked object using Moq and pass that in to create the object BClass2 depends on - in this case BClass1. Since your mocked object and BClass1 implements or inherits the same type, injecting the mocked object is good enough for BClass2-it won't know whether it's a real instance of BClass1 or one of it's siblings :)
This way, you have full control to unit test BClass2 and that is without even thinking about DClass.
The design of the program itself matters on testability. As long as its designed without tight coupling, Moq is really one of the best mocking framework that I know to make mocking much easier for unit test.
Happy Moqing :)

Hope this helps :)




--
--
Post: moq...@googlegroups.com
Unsubscribe: moqdisc-u...@googlegroups.com
---
You received this message because you are subscribed to the Google Groups "Moq Discussions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to moqdisc+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages