-1

I get NullReferenceException when I try to test my class and I have no idea why? Exeption is connected to: o1.Products.Add. When I try to delete it, everything is ok.

public class Product
{
    public string Name { get; set; }
    public decimal Value { get; set; }
}

public class Order
{
    public List<Product> Products { get; set; }

    private decimal value { get; set; }
    public decimal Value
    {
        get { return value; }
        set
        {
            if (Products.Count == 0)
                value = 0;
            else
                value = Products.Sum(x => Convert.ToInt32(x));
        }
    }
}

[TestClass]
public class Tests
{
    [TestMethod]
    public void OrderTest()
    {
        //Arrange
        Product p1 = new Product();
        Order o1 = new Order();
        //Act
        p1.Value = 10;
        o1.Products.Add(p1);
        //Assert
        Assert.AreEqual(30, o1.Value);
    }
}

1 Answers1

0

This happens because Products is never instantiated, so it is null - you are calling null.Add(p1), which is a null reference.

To fix it, you can create an Order constructor and instantiate Products there.

public class Order
{
    public List<Product> Products { get; set; }

    public Order() {
        this.Products = new List<Product>();
    }
}
James Monger
  • 8,229
  • 5
  • 44
  • 81
  • Downvoter: Why was this answer downvoted? It seems to have been downvoted at the same time as the question. If you feel that the question is a bad question, that does not necessarily mean that my answer is a bad answer. Please vote answers on their own merit. – James Monger Dec 29 '16 at 12:57
  • Thanks! It's realy great answer! – Tomasz Szymański Dec 29 '16 at 13:12