Home > Mobile >  Unit Testing - How to test content of variable in a method that returns something else?
Unit Testing - How to test content of variable in a method that returns something else?

Time:06-28

I have this pseudocode which I need to create Unit Test. How can I create unit test to verify content of x.name and x.type?

public async Task<T> functionA(Event eventData)
{
   var x = new ClassA();

   x.name = classB.name;
   x.type = classB.type;

  // Then adding x into a database

   return something like status.Success;
}

CodePudding user response:

You don't actually want to test the value of x.name and x.type: those are implementation details. What if you chose to use a different variable name, or avoid using a variable at all? It would be a pain to have to update your unit test when you didn't actually change the externally-observable behavior of your method.

What you really want to test is whether this function adds the appropriate values to the database. The ideal way to do this is to make sure that you're interacting with your database through a mockable dependency. For example, if you have an IClassARepository interface that you provide to your class as a parameter to its constructor, then the "adding x into a database" code you omitted might look like this:

this.classARepository.Save(x);

Then you can use a library like Moq to create a Mock instance of that repository to inject in the instance of your class that you're unit testing, and after calling your method, you could verify that the values you want are passed into the Save method.

repositoryMock.Verify(r => r.Save(It.Is((ClassA a) => a.name = "foo" && a.type == "bar")));
  • Related