Skip to content

Specifying a Call to Configure

One of the first steps in configuring a fake object's behaviour is to specify which call to configure. Like most FakeItEasy actions, this is done using a method on the A class: A.CallTo.

Specifying a method call or property get using an Expression

A.CallTo(() => fakeShop.GetTopSellingCandy())
A.CallTo(() => fakeShop.Address)

The expressions in the above example are not evaluated by FakeItEasy: no call to GetTopSellingCandy or Address is made. The expressions are just used to identify which call to configure.

A.CallTo returns an object that can be used to specify how the fake should behave when the call is made. For example:

A.CallTo(() => fakeShop.GetTopSellingCandy())
                       .Returns(lollipop);

Many types of actions can be specified, including returning various values, throwing exceptions, and more.

Specifying a call to a property setter

Assignment operators can't be used in lambda expressions, so the A.CallTo overloads described above cannot be used to configure calls to property setters. Use A.CallToSet to configure the set behavior of read/write properties:

A.CallToSet(() => fakeShop.Address).To("123 Fake Street").CallsBaseMethod();
A.CallToSet(() => fakeShop.Address).To(() => A<string>.That.StartsWith("123").DoesNothing();
A.CallToSet(() => fakeShop.Address).DoesNothing(); // ignores the value that's set

Argument constraints can be used to constrain the value that's set into the property, or the indexes that must be supplied when invoking an indexer.

Specifying a call to any method or property

Instead of supplying an expression to identify a specific method, pass the fake to A.CallTo to refer to any method on the fake:

A.CallTo(fakeShop).Throws(new Exception());

// Or limit the calls by return type
A.CallTo(fakeShop).WithReturnType<string>().Returns("sugar tastes good");

// Or create a sophisticated test with a predicate that acts on an IFakeObjectCall
A.CallTo(fakeShop).Where(call => call.Arguments.Count > 4)
                  .Throws(new Exception("too many arguments is bad");

A.CallTo(object) can also be used to specify write-only properties and protected members:

A.CallTo(fakeShop).Where(call => call.Method.Name == "ProtectedCalculateSalesForToday")
                  .WithReturnType<double>()
                  .Returns(4741.71);

// refers to the Address property's setter
A.CallTo(fakeShop).Where(call => call.Method.Name == "set_Address")
                  .Throws(new Exception("we can't move");

VB.Net

Special syntax is provided to specify Funcs and Subs in VB, using their respective keywords:

A.CallTo(Sub() fakeShop.SellSomething())
                       .DoesNothing()

A.CallTo(Func() fakeShop.GetTopSellingCandy())
                        .Returns(lollipop)