Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

unit testing - How to mock a function call on a concrete object with Moq?

How can I do this in Moq?

Foo bar = new Foo();
Fake(bar.PrivateGetter).Return('whatever value')

It seems I can only find how to mock an object that was created via the framework. I want to mock just a single method/property on a concrete object I've created.

In TypeMock, I would just do Isolate.WhenCalled(bar.PrivateGetter).Returns('whatever value').

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use Moq to create your Mock object and set CallBase property to true to use the object behavior.

From the Moq documentation: CallBase is defined as “Invoke base class implementation if no expectation overrides the member. This is called “Partial Mock”. It allows to mock certain part of a class without having to mock everything.

Sample code:

    [Test]
    public void FailintgTest()
    {
        var mock = new Moq.Mock<MyClass>();
        mock.Setup(m => m.Number).Returns(4);
        var testObject = mock.Object;
        Assert.That(testObject.Number, Is.EqualTo(4));
        Assert.That(testObject.Name, Is.EqualTo("MyClass"));
    }

    [Test]
    public void OKTest()
    {
        var mock = new Moq.Mock<MyClass>();
        mock.Setup(m => m.Number).Returns(4);
        mock.CallBase = true;
        var testObject = mock.Object;
        Assert.That(testObject.Number, Is.EqualTo(4));
        Assert.That(testObject.Name, Is.EqualTo("MyClass"));
    }

    public class MyClass
    {
        public virtual string Name { get { return "MyClass"; } }

        public virtual int Number { get { return 2; } }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...