-1

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

James Z
  • 12,209
  • 10
  • 24
  • 44
Atulya
  • 153
  • 1
  • 11
  • Have you got some code? I personally usually use wrappers that wrap the dependency and define an interface that describes the desired methods i am using which is implemented by the wrapper – SirOneOfMany Apr 12 '22 at 12:34
  • @SirOneOfMany I understand that you can mock the classes which are implementing interfaces or you have implemented dependency injection using interfaces. but here clientwebsocket is sealed system class, so I was looking for any standard procedure. – Atulya Apr 12 '22 at 12:50

1 Answers1

2

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

SirOneOfMany
  • 929
  • 5
  • 15