-2

Good day,

I'm begginer in xUnit and I'm facing this error that says, "System.NullReferenceException : Object reference not set to an instance of an object."

Here's my code where it tests whether a rulename depending on the season.

public class UnitTest1
{
    private CalculateDiscount calculateDiscount;

    [Fact]
    public void Setup()
    {
        calculateDiscount = new CalculateDiscount();
    }

    [Theory]
    [InlineData(10.00, "Summer", 100.00)]
    public void WhenRuleName_Is_Summer_Return_Valid(decimal amount, string ruleName, decimal expected)
    {
        var result = calculateDiscount.CalculateDiscountSalary(amount, ruleName);

        Assert.Equal(expected, result);
    }
}

And here is my actual implementation

public class CalculateDiscount
{
    public decimal CalculateDiscountSalary(decimal amount, string ruleName)
    {
        if (ruleName.Equals("Summer"))
        {
            return amount * 10.00M;
        }
        else if (ruleName.Equals("Winter"))
        {
            return amount * 15.00M;
        }
        else
        {
            return amount * 20.00M;
        }
    }
}

Thank you in advance.

jsonGPPD
  • 987
  • 4
  • 16
  • 31

2 Answers2

1

Fact do not have to run before Theory.

Your setup must be your constructor. If you change your setup function as constructor, your null reference exception problem is resolved

public UnitTest1()
{
    calculateDiscount = new CalculateDiscount();
}
Adem Catamak
  • 1,987
  • 2
  • 17
  • 25
0

I guess you are confused with XUnit and NUnit.

NUnit provides a SetUp Fixture to initialize variables that you can use repeatedly.

As of the moment, XUnit doesn't have. But there are workarounds.

KaeL
  • 3,639
  • 2
  • 28
  • 56