Reputation: 17714
Assume the following method overloads:
public string SayHello(string identifier)
{
return $"Hello {identifier}";
}
public string SayHello(long identifier)
{
return SayHello(identifier.ToString());
}
I would write a test for SayHello(string identifier)
like this:
Assert.Equal("Hello Max", SayHello("Max"))
What about SayHello(long identifier)
? Of course I could write
Assert.Equal("Hello 123", SayHello(123))
but imagine the logic for SayHello would be far more complex. Then I basically would have to write the same unit test twice with only slight changes. So, is there any better approach? Maybe just check if / assert that SayHello(long identifier)
ONLY calls SayHello(identifier.toString())
? Is that possible?
Upvotes: 0
Views: 56
Reputation: 17248
In this particular case, since neither of the methods are virtual and both are in the same class, you can't test SayHello(long)
without testing SayHello(string)
. There's no way to intercept the call to SayHello(string)
without changing the code (or maybe perform some really ugly hacks). You could of course introduce some callback interface in there or some unit-test-only flags, but all of that requires adjusting the code so that it's testable the way you want it. Personally, I'm not a fan of increasing the complexity of some code pieces just for the sake of testability.
So unless the methods are really complex, I would just go with testing them together, maybe by using a theory approach (combinatorial test cases). Note that if you one time change your SayHello(string)
to return $"Bye {identifier}";
you'd have to change all test cases anyway.
Upvotes: 1