Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking virtual readonly properties with moq

People also ask

How do I mock a read only property?

you can set up Foo (a read-only property) like this: var stub = new Mock<MyAbstraction>(); stub. SetupGet(x => x. Foo).

What can be mocked with Moq?

Unit testing is a powerful way to ensure that your code works as intended. It's a great way to combat the common “works on my machine” problem. Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation. Moq is a mock object framework for .

Can you mock a class with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

Can we use Moq with NUnit?

We will install NUnit and Moq using the Nuget package manager. Make sure that in your references, NUnit and Moq are present after installation: For running NUnit tests and exploring the tests, we need to install a visual studio extension called “NUnit 3 Test Adapter”.


Given this class

public abstract class MyAbstraction
{
    public virtual string Foo
    {
        get { return "foo"; }
    }
}

you can set up Foo (a read-only property) like this:

var stub = new Mock<MyAbstraction>();
stub.SetupGet(x => x.Foo).Returns("bar");

stub.Object.Foo will now return "bar" instead of "foo".


You need to make sure property is virtual to make this work.