you can set up Foo (a read-only property) like this: var stub = new Mock<MyAbstraction>(); stub. SetupGet(x => x. Foo).
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With