0

I have a c# class that gets object property names.

public class MyClass
{
    public int Id { get; set; }
    public int Name { get; set; }
}

public class Parser<T>
{
    public IEnumerable<string> Parse(T item)
    {
        const BindingFlags flag = BindingFlags.Instance | BindingFlags.Public;

        return item.GetType().GetProperties(flag).Select(p => p.Name);
    }
}

I want to test this methot.

    [Test]
    public void TestMethod()
    {
        var parser = new Parser<MyClass>();
        var names = parser.Parse(new MyClass()).ToArray();

        Assert.IsTrue(names[1] == "Name");
    }

But this throws an exception System.NullReferenceException. But I put breakpoint and see names array have two items.

Assert.IsTrue(names[1] == "Name"); row throws exception. But is has 2 items.

Test 'M:ParsProejct.TestsClass.TestMethod.' failed: Object reference not set to an instance of an object.

barteloma
  • 5,342
  • 7
  • 55
  • 126
  • Why are you using `Assert.IsTrue` (which will never give you much information) rather than `Assert.AreEqual` to start with? I doubt that it will fix things, but it's a good habit to get into. – Jon Skeet Jul 12 '17 at 06:19
  • I tried `Assert.AreEqual(names[0], "Name");` now, but did not work. – barteloma Jul 12 '17 at 06:22
  • Right. But it's something you should use (the other way round) in future. For now, you need to work out what's null. To improve this question, you should a) make it a [mcve]; b) include the full stack trace rather than just the message. – Jon Skeet Jul 12 '17 at 06:27
  • 1
    What are you using to run your tests? NUnit asserts can throw a NullReferenceException if they are not run within an NUnit runner. I would recommend running in nunit3-console.exe to give you more information. – Rob Prouse Jul 12 '17 at 15:48
  • I am using NUnit – barteloma Jul 13 '17 at 06:04

0 Answers0