C# Unit Testing in C# Test Driven Development TDD

help please

Implement the Subtract method so that the test passes.

Calculator.cs
public class Calculator
{
    public double Result;

    public Calculator(double number)
    {
        Result = number;
    }     

    public void Add(double number)
    {
        Result += number;
    }

    public void Subtract(double number)
    {
        Result -= number;
    }
}
CalculatorTests.cs
using Xunit;

public class CalculatorTests
{
    [Fact]
    public void Initialization()
    {
        var expected = 1.1;
        var target = new Calculator(1.1);
        Assert.Equal(expected, target.Result, 1);
    }

    [Fact]
    public void BasicAdd()
    {
        var target = new Calculator(1.1);
        target.Add(2.2);
        var expected = 3.3;
        Assert.Equal(expected, target.Result, 1);
    }
     [Fact]
    public void BasicSubtract()
    {
        var target = new Calculator(1.1);
        target.Substract(0.2);
        var expected = 0.9;
        Assert.Equal(expected, target.Result);
        Assert .Equal(double expected,double actual,int precision);
    }

}

1 Answer

Steven Parker
Steven Parker
179,610 Points

I see 3 issues, all in the BasicSubtract testing method:

  • there is a reference to "target.Substract" (with an extra "s") instead of "target.Subtract"
  • the (first) call to "Assert.Equal" is missing the third argument
  • the second call to "Assert.Equal" is not needed and is improper syntax

thank you Steven but the third argument am totally lost what is it ....?

Steven Parker
Steven Parker
179,610 Points

The third argument specifies the precision. Take a look at the call done in the BasicAdd function as an example.