Disappointed Disappointed - 3 months ago 12
C# Question

Is it ok to write unit tests for private method for this Expression evaluator class?



I have tho following code

public interface IInterpreter
{
decimal Evaluate(string expression);
}

public class Interpreter : IInterpreter
{
public decimal Evaluate(string expression)
{
if (String.IsNullOrWhiteSpace(expression))
throw new ArgumentException("Parameter " + nameof(expression) + " cannot be empty");

var rpnExpression = ConvertToReversePolishNotation(expression);
return EvaluateReversePolishExpression(rpnExpression);
}
...
}


This class will evaluate expressions like "5+5*6" or "(3-5)*(2+2) +5"

Now i want to write unit tests. The only public function here is
Evaluate
and according to all recomendation only this method should be tested.

The problem is that i have a strong feeling that both
ConvertToReversePolishNotation(expression)
EvaluateReversePolishExpression(rpnExpression)
functions have to be covered with unit tests ... If some unit test will fail for
Evaluate
method it will not point me out where is the bug (in
ConvertToRPNExpression
method or in
EvaluateReversePolishExpression
function).




So the question is - Is it ok in this case to write unit tests for private functions ?

Answer

No.

Refactor the ConvertToReversePolishNotation method to a seperate class. Its concern is conversion.

The concern of the Interpreter is to evaluate. If you 'mock' the output of the conversion it should be easy to test using the public Evaluate method.

Comments