1

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!

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

Comments

-3

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.

2 Comments

This doesn't solve the problem as Bar in the original interface is still read-only
additionally changing production code in order for tests to behave well, is not a good idea in maybe all cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.