Reputation: 2837
I am trying to mock a webservice object that inherits from SoapHttpClientProtocol
and that I can't modify in my unit test. Unfortunately when I try:
var myApi = Substitute.ForPartsOf<MyAPIClass>();
I get the following error:
Message: Test method MyProj.Test.Business.Folder.CalendarEventServiceUnitTest.GetPerformances_WithEventsAndPerformances_CorrectlyDistinguishesThem threw exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: There was an error reflecting type 'MyNamespace.MyAPIClass'. ---> System.InvalidOperationException: Cannot serialize member 'System.ComponentModel.Component.Site' of type 'System.ComponentModel.ISite', see inner exception for more details. ---> System.NotSupportedException: Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface.
Upvotes: 2
Views: 702
Reputation: 247283
Do not try to mock code you have no control over (ie. 3rd party code). Abstract the desired behavior and encapsulate 3rd party code in your implementation of the abstraction.
public interface IMyApiInterface {
//...code removed for brevity
}
Inject the abstraction into their dependents classes. This would allow for better mocking with your unit tests and overall a more flexible/maintainable architecture.
var myApi = Substitute.For<IMyApiInterface>();
The actual implementation of the interface would encapsulate or compose the actual web service.
public class MyProductionAPIClass : MyAPIClass, IMyApiInterface {
//...code removed for brevity
}
Do not tightly couple your code to implementation concerns that do not allow for flexible and maintainable code. Instead depend on abstractions.
Upvotes: 2