Hi I have created a class which has a method to return a string "HelloWorld"

Here is the code

public class Class1
{

    public string GetHelloWorld()
    {
        return "HelloWorld";
    }
}

I have written a NUnit Test case and want to mock the return string for this method as below

 public class UnitTest1
{
    Mock<Class1> mock;
    [Test]
    public void TestMethod1()
    {
        string expected = "Hi";
        mock.Setup(m => m.GetHelloWorld()).Returns(()=>"Hi");
        Class1 obj = new Class1();
        string x=obj.GetHelloWorld();
        Assert.AreEqual("Hi", x);

    }
}

When I am running with Nunit,I am getting the error as "Object reference not set to an instance of an object" on line 15 which is mock.setup

Can anybody help me in resolving this issue to make this unit test pass.

Thanks for your help on this.

有帮助吗?

解决方案

You haven't assigned a value to the mock field. Add the following line to your test.

Mock<Class1> mock = new Mock<Class1>()

You won't be able to mock that method anyway because it's not virtual. See this question for more info: Moq: Invalid setup on a non-overridable member: x => x.GetByTitle("asdf")

Finally, the behaviour you set up only applies to the instance that you retrieve from your mock with the mock.Object property, not to normal instances of Class1. So if you instantiate a new Class1(), you won't get the mocked behaviour.

In summary, your code would have to look more like this:

public class Class1
{
    public virtual string GetHelloWorld()
    {
        return "HelloWorld";
    }
}

public class UnitTest1
{
    [Test]
    public void TestMethod1()
    {
        //arrange
        Mock<Class1> mock = new Mock<Class1>();
        mock.Setup(m => m.GetHelloWorld()).Returns(()=> "Hi");
        Class1 obj = mock.Object;

        //act
        string x = obj.GetHelloWorld();

        //assert
        Assert.AreEqual("Hi", x);

    }
}

其他提示

I can't see any Mock<Class1> mock = new Mock<Class1>(). Maybe it is missing and therefore leads to the NullReferenceException.

Secondly, it's not possible to mock a non virtual method with Moq. So your class would need to look like this.

public class Class1
{
    public virtual string GetHelloWorld()
    {
        return "HelloWorld";
    }
}

But also I'm not really sure what you're trying to do... Why do you setup a mock when in the end you call the method on the real implementation?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top