Jack M
Jack M

Reputation: 2574

Unit Test on overloaded method

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

Answers (2)

Paolo Falabella
Paolo Falabella

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:

  • loading a client from the DB (by product Id?)
  • checking (with complex logic involving more queries to the db?) what kind of client it is

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

Leigh Ciechanowski
Leigh Ciechanowski

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

Related Questions