13. var mock = new Mock<ILoveThisFramework>();
// WOW! No record/replay weirdness?! :)
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
.Returns(true)
.AtMostOnce();
// Hand mock.Object as a collaborator and exercise it,
// like calling methods on it...
ILoveThisFramework lovable = mock.Object;
bool download = lovable.DownloadExists("2.0.0.0");
// Verify that the given method was indeed called with the expected
value
mock.Verify(framework => framework.DownloadExists("2.0.0.0"));
Moq
14. // Creating a fake object is just dead easy!
// No mocks, no stubs, everything's a fake!
var lollipop = A.Fake<ICandy>();
var shop = A.Fake<ICandyShop>();
// To set up a call to return a value is also simple:
A.CallTo(() => shop.GetTopSellingCandy()).Returns(lollipop);
// Use your fake as you would an actual instance of the faked type.
var developer = new SweetTooth();
developer.BuyTastiestCandy(shop);
// Asserting uses the exact same syntax as when configuring calls,
// no need to teach yourself another syntax.
A.CallTo(() => shop.BuyCandy(lollipop)).MustHaveHappened();
FakeItEasy
15. Mock object Object Expression
Mock<IShopDataAccess>() { new IShopDataAccess with
.Setup(fun data -> member __.GetProductPrice(productId) =
<@ data.GetProductPrice(any()) @>) match productId with
.Calls<int>(function | 1234 -> 45M
| 1234 -> 45M | 2345 -> 15M
| 2345 -> 15M | _ -> failwith "Unexpected"
| productID -> failwith "Unexpected" member __.Save(_,_) =
) failwith "Not implemented"
.Create() }
F# Object Expressions
19. var order =
new Mock<IOrder>()
.SetupProperties(new {
Price = 99.99M,
Quantity = 10,
Side = Side.Bid,
TimeInForce = TimeInForce.GoodTillCancel
})
.Create();
Assert.AreEqual(99.99M, order.Price);
Assert.AreEqual(10, order.Quantity);
Assert.AreEqual(Side.Bid, order.Side);
Assert.AreEqual(TimeInForce.GoodTillCancel,
order.TimeInForce);
Foq: Anonymous Type
20. let [<Test>] ``order sends mail if unfilled`` () =
// setup data
let order = Order("TALISKER", 51)
let mailer = mock()
order.SetMailer(mailer)
// exercise
order.Fill(mock())
// verify
verify <@ mailer.Send(any()) @> once
Foq: Type Inference
21. let [<Test>] ``verify sequence of calls`` () =
// Arrange
let xs = Mock.Of<IList<int>>()
// Act
xs.Clear()
xs.Add(1)
// Assert
Mock.VerifySequence
<@ xs.Clear()
xs.Add(any()) @>
Foq Sequences
25. Setup a mock method in C# with a lambda expression:
new Mock<IList<int>>()
.Setup(x => x.Contains(It.IsAny<int>())).Returns(true)
.Create();
Setup a mock method in F# with a Code Quotation:
Mock<System.Collections.IList>()
.Setup(fun x -> <@ x.Contains(any()) @>).Returns(true)
.Create()
LINQ or
Quotations