iLemming
iLemming

Reputation: 36166

Property that depends on Mocked property

How can I mock and setup one property the way that any other member that based on that property won't need to have a setup.

public interface IFoo{
    public Foo  { get; set; }
    public Foo2 { get; }
}

public class Foo :IFoo{
    public Foo  { get; set; }
    public Foo2 { get {return this.Foo +" second";} }
}


public void FooTest(){
    var f = Mock<IFoo>();
    f.SetupGet(x=> x.Foo).Returns("Foo");

    // Should print 'Foo second' although there's no setup for Foo2
    Console.Write(f.Object.Foo2); 
}

Upvotes: 1

Views: 76

Answers (3)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

In your question, it's confusing (and illegal in C#) that the property Foo inside the class Foo has the same name as the class of which it is a member. Also you're missing the types of your properties (presumably string). So please come up with some code that compiles.

After you've done that, I think it will be clear that your Mock<> refers only to the interface IFoo. There could be many classes and structs implementing IFoo. How could Moq know that you were think about the class Foo in which there is a connection between the getters of the two properties?

The IFoo cannot specify any required relation between the two properties; it is an interface.

Upvotes: 2

Mark Walsh
Mark Walsh

Reputation: 3361

Not entirely sure why you wish to do this, but my first thought is to use Reflection to loop through the members of the class and setup each one of them, although, not sure really sure why anyone would do this. I am guessing you're trying to save time?

Although not completely applicable, you could mould this to your needs as it is relevant:

Generating mock objects for test cases

Upvotes: 1

Brian S
Brian S

Reputation: 5785

In your example, you are creating a mock of the IFoo interface, so there's no implementation of the Foo2 property. The implementation of the Foo object is irrelevant in this case because you never instantiate a Foo object. f is a mock of IFoo, and therefore does not have any relationship to the object Foo except that they both implement the same interface. Have you tried something like this?

var f = Mock<IFoo>();
f.SetupGet(x => x.Foo).Returns("Foo");
f.SetupGet(x => x.Foo2).Returns(f.Foo + "Second");

I'm not exactly sure what you're trying to accomplish, however, so I'm guessing.

Upvotes: 2

Related Questions