You need to inject an instance of MyClass either as a constructor parameter, a property or a method parameter. You can then mock it and pass in an instance of the mock, or depending on your code it might not be necessary to mock it and you can just pass an instance of MyClass with the properties set for the test.
To pass MyClass via the constructor:
public class ClassThatUsesMyClass { private readonly MyClass _myClass; public ClassThatUsesMyClass(MyClass myClass) { _myClass = myClass; } public async Task<MyResponse> Handle(MyRequest request, CancellationToken cancellationToken) { // This method uses the _myClass field instead of creating an instance of MyClass } }
Or as a method argument:
public class ClassThatUsesMyClass { public async Task<MyResponse> Handle(MyRequest request, MyClass myClass, CancellationToken cancellationToken) { // This method uses the myClass argument instead of creating an instance of MyClass } }
In both cases the class receives an instance of MyClass instead of creating it. That's what we call dependency injection. (MyClass is the dependency, that is, the thing this depends on, or needs.)
Because it's passed in as an argument, the unit test is able to set its properties first.