60

I couldn't find a way to do this, though this can be done by hand so why not with moq?

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
gkdm
  • 2,375
  • 4
  • 21
  • 27

2 Answers2

101

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".

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • excellent answer thank you. another words, it's better to not have getter-only properties because they are a pain in the ass to mock? – Alex Gordon Mar 06 '16 at 12:39
  • you see i have a bunch of read only properties: https://drive.google.com/file/d/0ByqKtGmtuLzZNFhwTWhMMGVRZnc/view?usp=drivesdk and i am trying to use their parent class as the system under test, so im not sure how i would setup the moq, since the system under test is not a mocked class, whereas i want to force a value from those getters – Alex Gordon Mar 06 '16 at 12:41
  • 2
    @l--''''''---------'''''''''''' A get-only property is only syntactic sugar over a method, so if you take that statement to its logical conclusion, you'd be saying that it's better not to have methods that return data. I don't agree with that at all. – Mark Seemann Mar 06 '16 at 12:41
  • great point. could you suggest how i can inject those getters into a concrete (non mocked) class? – Alex Gordon Mar 06 '16 at 12:46
  • apologies if i am not making much sense, thats part of the problem, i just need a way to express/describe this – Alex Gordon Mar 06 '16 at 12:54
  • @l--''''''---------'''''''''''' That sounds like a candidate for a new question here on Stack Overflow :) – Mark Seemann Mar 06 '16 at 12:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/105481/discussion-between-l-and-mark-seemann). – Alex Gordon Mar 06 '16 at 12:54
  • here you are, sir http://stackoverflow.com/questions/35827217/how-to-mock-inject-a-getter-into-a-system-under-test – Alex Gordon Mar 06 '16 at 13:11
2

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

  • When answering an old question which already has an accepted answer, please try to give an answer which either adds something new or is otherwise helpful in relation to it. As your current answer is right now it's more a comment than an answer. Apart from stating what needs to be ensured for something to work it's usually much more helpful to also include a specific example on how to do it. See also the [contribution guide](https://stackoverflow.com/help/how-to-answer) for reference. – Ivo Mori Oct 07 '20 at 02:47