How to test a COM dependent object in C#

半腔热情 提交于 2019-12-03 20:59:44

问题


I´m trying to do TDD with an object that has a dependency on a COM Interface. I though about mocking the COM interface, while doing development testing, and do it real on the integration tests.

However, I cannot mock the COM interface, I tried with Moq, and it throws an exception:

System.TypeLoadException was unhandled by user code Message=Could not load type 'Castle.Proxies.iTunesAppProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. The type is marked as eligible for type equivalence, but either it has generic parameters, or it is not a structure, COM imported interface, enumeration, or delegate

Is it possible with other frameworks? How do you do TDD with COM dependent objects?

Thanks in advance!or delegate


回答1:


I would suggest that you take ownership of the interface of the COM object, this is where Dependency Inversion Principle would come into play.

If you don't have access to the source, you will have to create your own abstraction that wraps the COM Object, otherwise you will have third-party calls throughout your code.

[EDIT]

Now the abstraction should be able to be mocked. The actual implementation of the wrapper will have the COM object as a HAS-A relationship.

You will then want to have an integration test for the implementation.

You need to treat the COM object itself as if it was something similar to a database or graphic rendering engine or a web service.




回答2:


Try to set "Embed Interop Types" to FALSE for assembly that contains COM interface.




回答3:


You need to add the following in the initialization part like explained here https://code.google.com/p/moq/issues/detail?id=254

Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof (TypeIdentifierAttribute));



回答4:


OK, I thing there is no straightforward way of doing that, not sure that some of mocking frameworks could mock COM.

What I have in my mind..

You have some COM interface, ISomeThing and COM object implements this interface CoSomeThing, this some real implementation. You should implemenent yet another COM component, that would implement same interface, but actually just mocking it - CoSomeThingMock.

In your code you instantiate CoSomeThingMock, instead of CoSomeThing and use it.

var component = new CoSomeThingMock();
var testObject = new Tested(component);


来源:https://stackoverflow.com/questions/3223991/how-to-test-a-com-dependent-object-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!