Reputation: 2574
I have been battling with writing some unit test for some of our code and I am struggling with this one:
We have a method that we overloaded and it is like this:
Public Client GetClient(int productID)
{
//Some sql that evaluate a client
if(!GetClient(clientRef,ClientTypeRef))
Return Client.UnknownClient;
//some other sql and codes
Return Client.CustomerClient;
}
The problem is how do I approach this, in my test I tried to add a mock to the GetClient(clientRef,ClientTypeRef)
and returning an OK Client (anything other than Client.UnknownClient
) to allow me to continue but I am getting a null reference? Is it possible to mock and test such methods, and how would I continue with this.
Upvotes: 1
Views: 2302
Reputation: 25844
One of the reasons why unit testing has become so popular was that it was shown to encourage SOLID design principles.
Based on the little piece of code you've included, I think your difficulty may come from the fact that your GetClient(int productID)
has too many responsibilities so you're struggling to test them separately.
The way I understand it, you are:
Rather than mocking GetClient(clientRef,ClientTypeRef)
so that you can test every logical path under it, I would encourage you (if possible) to try and refactor your code, so that you separate the loading of the client from the checking of the client's type and possibly also some of the logic you group under //some other sql and codes
.
That should make it easier to test every piece separately, but above all would make your code more maintainable.
Upvotes: 2
Reputation: 1317
What mocking frame work are you using?
I use moq, to mock this method you would do something like
_mockClientRepository.Setup(x => x.GetClient(It.IsAny<int>(),It.IsAny<int>())).Returns(Client.CustomerClient);
Basically this means that any integer passed to the method will always return Client.CustomerClient
Upvotes: 1