Im doing some research. I want to use moq and pass it to an MVC controller so allow it to set some values in session. I have written some code to see if its possible to 'open up' a property with no setter. Just don't know if its possible...
The following code was my attempt at trying to set a property witn no setter!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Moq;
namespace TestMoq
{
class Program
{
static void Main(string[] args)
{
var mock = new Mock<TestClass>();
mock.SetupProperty(f => f.VarWithNoSetter);
mock.Object.VarWithNoSetter = "Set";
Console.WriteLine(mock.Object.VarWithNoSetter);
Console.ReadLine();
}
}
public class TestClass
{
private string _varWithNoSetter;
public string VarWithNoSetter
{
get { return _varWithNoSetter; }
}
public TestClass()
{
}
}
}
You can set the mock object property to the value returned by the mock object method. To achieve this, specify separate behaviors for the method and the property. You can specify one behavior at a time. For more information about mock object behavior, see Specify Mock Object Behavior.
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.
First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.
'Setup' mocks a method and 'Returns' specify what the mocked method should return. 'Verifiable' marks this expectation to verified at the end when Verify or VerifyAll is called i.e. whether AddIncomePeriod was called with an object of IncomePeriod and if it returned the same output.
Sure:
mock.SetupGet(f => f.VarWithNoSetter).Returns("Hi, Exitos!");
For me it doesn't work with SetUpGet, without making the property virtual. However it works by using Mock.Of<>:
var mock = Mock.Of<TestClass>(m=>m.VarWithNoSetter == "the value");
Yes you can but you have to make that property virtual at it will be possible as Moq will generate a proxy
public virtual string VarWithNoSetter
{
get { return _varWithNoSetter; }
}
or you can use .SetUpGet
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