Stamatis Tiniakos
Stamatis Tiniakos

Reputation: 843

NUnit Test - How to set up a private method called inside public method to return specific value?

I am trying to test the following GetNumber public method using NUnit.

public GetNumber()
{
   var numberOfUsers = GetNumberOfUsers();
   var number = numberOfUsers + 1;

  return number;
}  

To test it fully I need the private GetNumberOfUsers method to return a specific value during the execution of the test e.g. 0 or 1. How can I set up my test so that GetNumberOfUsers returns the values that I want?

The logic of the test will be something like the below:

[Test]
public void GetNumberTest()
{

   //setup GetNumberOfUsers so that it returns 0

   var result = object.GetNumber();

   Assert.AreEqual(1, result);

}

Upvotes: 0

Views: 270

Answers (1)

Andrew
Andrew

Reputation: 5277

You can't. You should be aiming to test your public interface. You haven't given enough detail about where GetNumberOfUsers gets it's result from which makes it difficult to give you the optimum solution. You could make GetNumberOfUsers protected and override it in a subclass. e.g.

public class MyClass
{
  public int GetNumbers()
  {
    var numberOfUsers = GetNumberOfUsers();
  }

  protected virtual GetNumberOfUsers()
  { // implementation } 
}

public class MyClassImplForTesting : MyClass
{
  public int NumberOfUsers {get; set;} = 10;
  protected overrides GetNumberOfUsers()
  {
    return NumberOfUsers;
  }
}

Upvotes: 1

Related Questions