Reputation: 23
I am having trouble unit testing below method. I cant mock MyClass
but I need to fill up the props in it to be able to unit test the rest of the method. Is it possible to create MyClass
instance and evaluate in a unit test?
public async Task<MyResponse> Handle(MyRequest request, CancellationToken cancellationToken)
{
MyClass obj = new MyClass();
_dependecy.Execute(obj);
foreach(var o in obj.Props)
{
//do some processing
}
}
Upvotes: 1
Views: 70
Reputation: 11871
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.
Upvotes: 3