c# - How to mock a method called inside another method? -
i explain problem using example.
class { fun1() { // code b obj2 = new b(); obj2.fun2(); } } class b { fun2() { // code } } // test class class class a_test { fun1_test() { obj1 = new a(); a.fun1(); } } here calling fun1 calls fun2(). want mock phone call fun2().
i need initialization of class b object in fun1() only, don't want using constructor.
it possible mock phone call fun2()?
you can't, because fun2 instance method of object created inside fun1.
since a depends on b, b should injected a, if want accomplish true isolation.
you should "depend upon abstractions", advertised dependency inversion principle. create b implement interface ib, , create a depend on ib instead. then, mock interface ib , inject mock instead.
class { public fun1(ib ib) { ib.fun2(); } } interface ib { fun2(); } class b : ib { public fun2() {} } // test class class class a_test { fun1_test() { var bmock = new mock<ib>(); bmock.setup(b => b.fun2()); obj1 = new a(); a.fun1(bmock.object); } } read:
dependency inversion principle dependency injection c# unit-testing moq
No comments:
Post a Comment