Question

This question is more like open discussion. I would like to start with an example. Suppose there is one service FooService

public interface IFooService { void Method1(){}}
public class FooService: IFooService { void Method1(){ ... }}

In order to test the service , we write the unit test code like below, no external services

public void TestMethod1(){ ... }

Then suppose in Method1 we need to use another class called AService which inherit from IAService

public interface IAService {void AMethod1(){}}
public class AService : IAService { void AMethod1() {}}
public class FooService : IFooService { 
    private IAService a;
    public FooService (IAService a){ this.a = a;}
    void Method1(){ a.AMethod1(); ..... business logic ..... }
}

Then we have to refactor the unit test to mock AService

public void TestMethod1(){
     IMockAService aService = MockRepository.StrickMock<IAService>();
     .....
}

So when need more external services, we have to add mock service, if some of services changed the logic or add or remove parameters, and so on. If there are 100 test cases, we have to modify all of test cases.

So what's the best solution for mocking increasing external services and effective way to handle any changes of external dependencies for example : add/remove parameters of methods.

thanks

Was it helpful?

Solution

Most times for me it's enough to create the class under test in a Setup method, leaving you with only one place to adapt when the constructor signature changes.

Alternatively you can move construction of the class under test to a private method.

Same goes for methods. Often you can wrap the call to a method under test in a private method. This is especially helpful, if you don't have to set up all passed parameters in every test, but can use defaults, which you might have prepared in your Setup method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top