Unit test method that calls the wcf service

How is the unit test a business layer method that invokes a WCF service call?

Example:

public void SendData(DataUnit dataUnit) { //this is WCF call SomeServiceClient svc = new SomeServiceClient(); svc.SomeMethod(dataUnit); } 

Is there a way I can mock SomeServiceClient in my unit test project?

+7
source share
2 answers

Your problem is that you closely linked your business layer to your WCF service — you are actually creating a new instance of the service client in the business layer, which means that it is now impossible to call the SendData method without calling the service methods.

The best solution here is to inject dependency injection into your architecture.

In its simplest case, all you do is pass the instance of your service class to your business layer. This is often done when building a class using a constructor parameter.

 public class BusinessClass { private ISomeServiceClient _svc; public BusinessClass(ISomeServiceClient svc) { _svc = svc; } public void SendData(DataUnit dataUnit) { _svc.SomeMethod(dataUnit); } } 

Note that the code above is a design pattern that is completely independent of any structure, such as the Inversion of Control container.

If your company policy does not use such frameworks (crazy policy, by the way), you can still manually enter your layouts into the service inside your unit tests.

+12
source

You must separate your business call from your business level:

Using the demo below, your business-level method that you specified will now look like this:

 public void SendData(IMyInterface myInterface, DataUnit dataUnit) { myInterface.SomeMethod(dataUnit); } 

Go to RealThing if you want to make a service call, pass TestThing if you just want to run a test:

 public interface IMyInterface { void SomeMethod(DataUnit x); } public class RealThing : IMyInterface { public void SomeMethod(DataUnit x) { SomeServiceClient svc = new SomeServiceClient(); svc.SomeMethod(x); } } public class TestThing : IMyInterface { public void SomeMethod(DataUnit x) { // do your test here } } 
+1
source

All Articles