1

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 } } 
1
  • Since you're newing the class in the method you're trying to test: no. You cannot. Because you are creating the object in the method to be tested. If you pass the object to the method, you can determine what goes in. Which could be a mock or an instance created specifically for the test. Commented Jul 3, 2019 at 9:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.