开发者

Is it possible to cast a interface based mock into object?

开发者 https://www.devze.com 2023-02-13 13:05 出处:网络
in fact I have a mock object based on the interface. I would like to cast him into the real object.. var BM = new Mock<DAL.开发者_开发技巧INTERFACES.IMYCLASS>();

in fact I have a mock object based on the interface. I would like to cast him into the real object..

    var BM = new Mock<DAL.开发者_开发技巧INTERFACES.IMYCLASS>();

Is it possible to cast the mock to retrieve a MYCLASS object?

Thanks for responses..


No, that's not how most mocking libraries work.

What they do is create a whole new object, implementing the interface you ask for.

As such, the underlying object is not a MYCLASS object at all, it's something else altogether.

If you need to mock a concrete class, use a mocking library that can mock classes, and change your code to be (similar to):

var BM = new Mock<DAL.INTERFACES.MYCLASS>();


Using moq allows you to test your class, which relies on other classes/interfaces, without needing to instantiate them.

If you want an instance of an object which implements your interface, you can simply call Object on your member:

var BM = new Mock<DAL.INTERFACES.IMYCLASS>();
BM.Object;

Don't forget to setup the required methods your testclass relies on. Further information can be found on the QuickStart guide on the moq homepage.


FYI, the mocking libraries subclass the target type behind the scenes.

So when you ask for Mock<IInterface>(), you get an implementation of that interface, creates at rubtime like so:

//Your code

public interface IInterface {
 //methods
}

public class Implementation : IInterface{
  //methods
}

//At run time

public class IInterfaceImplementataionWithAReallyLongName354234234235423kjh23r54234 : IInterface {
 //methods
}

What you originally wanted to achieve is not actually possible because your implementation of IInterface is nowhere to be seen when Moq creates a proxy for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消