Best way to mock System.Net.WebSockets ClientWebSocket class to unit test (nunit)

593 views Asked by At

I have used ClientWebSocket class for webSocket communication. What is the best way of mocking the class?

1

There are 1 answers

0
SirOneOfMany On

Let us assume you have the following code

class MyDependentClass {

    private AnyDependency _dependency;
    MyDependantClass(AnyDependency dependency){
        _dependency = dependency;
    }

    void DoSomethingWithDependency() {
        _dependency.MethodCall();
    }
}

In your unit test, you can either create an Instance of AnyDependency with mocked parameters. Or, and that is what I would suggest, you encapsulate your dependency and invert it.

interface IAnyDependencyWrapper {
   void MethodCall();
}

Then create a class that implements your interface and that uses AnyDependency

class AnyDependencyWrapper : IAnyDependencyWrapper {

    private AnyDependency _dep;
    AnyDependencyWrapper(AnyDependency dep){
       _dep = dep;
    }
    
    void MethodCall(){
        _dep.MethodCall();
    }
}

and then inject it in your class:

class MyDependentClass {

    private AnyDependency _dependencyWrapper;
    MyDependantClass(IAnyDependencyWrapper dependencyWrapper){
        _dependencyWrapper = dependencyWrapper;
    }

    void DoSomethingWithDependency() {
        _dependencyWrapper.MethodCall();
    }
}

Now the dependency is decupled from your code and you can mock IAnyDependencyWrapper. With this solution you can also change the implementation of IAnyDependencyWrapper at any time e.g. you change the dependency or have to update with breaking changes