Mike Perrenoud
Mike Perrenoud

Reputation: 67918

Error Setting up Property During Unit Testing Using Moq

Alright, let's assume I have a class like the following ...

public class Foo : IFoo
{
    public string Bar
    {
        get { ... }
    }

    public void Initialize()
    {
        ...
    }
}

... and as you can see it implements an interface so I can mock it. Now, in my unit test I'm building the mock like this ...

var mock = new Mock<IFoo>();
mock.SetupProperty(p => p.Bar).SetReturnsDefault("Some static value here.");

... however, when the test runs I get the following error ...

System.ArgumentException: Property IFoo.Bar is read-only. Parameter name: expression

So, three questions:

  1. What am I doing wrong?
  2. What do I need to do?
  3. Can you please explain how I misunderstood SetReturnsDefault?

Thanks all!

Upvotes: 1

Views: 1117

Answers (2)

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

Obviously, the error message is telling you that you can't mock the read-only property like that. Instead, try:

mock.SetupGet(p => p.Bar).Returns("whatever");

If you want ALL string properties which are not explicitly set up to return some string then do this:

mock.SetReturnsDefault<string>("whatever"); 
// IMPORTANT: don't call mock.SetupGet(p => p.Bar) as it will override default setting

Upvotes: 11

Deepak Rohilla
Deepak Rohilla

Reputation: 95

try this:-

public class Foo : IFoo
{
    priave string bar;
    public string Bar
    {
        get { ... }
        set {bar=value;}
    }

    public void Initialize()
    {
        ...
    }
}

You must have to specify Set. Otherwise it will be read only.

Upvotes: -3

Related Questions