Mocking with Moq

37
MOCKING WITH MOQ A look at mocking objects with the Moq framework By: Mohamed Elkhodary

Transcript of Mocking with Moq

Page 1: Mocking with Moq

MOCKING WITH MOQ A look at mocking objects with the Moq frameworkBy: Mohamed Elkhodary

Page 2: Mocking with Moq

YOUR EXPECTATIONS

Page 3: Mocking with Moq

TEST DRIVEN DEVELOPMENT

If it's worth building, it's worth testing.If it's not worth testing, why are you wasting your time

working on it?

Page 4: Mocking with Moq

TEST DRIVEN DEVELOPMENT

Page 5: Mocking with Moq

THE PROBLEM

Page 6: Mocking with Moq

SOLUTION

Page 7: Mocking with Moq

INTRODUCTION What is mocking?

Page 8: Mocking with Moq

TERMINOLOGIESo Mocks used to define expectations. Like expecting that method A() to be called with defined parameters. Mocks record and verify such expectations.o Stubs do not record or verify expectations, but rather allow us to “replace” the behavior and state of the “fake” object in order to utilize a test scenario.o Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.

Page 9: Mocking with Moq

MOCKING AN OBJECTo Mock objects are simulated objects that mimic the behavior of real objects in controlled ways. o A programmer typically creates a mock object to test the behavior of some other object.

Page 10: Mocking with Moq

REASONS FOR USEo The object supplies non-deterministic results (e.g., the current time or the current temperature).o It has states that are difficult to create or reproduce (e.g., a network error).o It is slow (e.g., a complete database, which would have to be initialized before the test).o It does not yet exist or may change behavior.o Testing it is out of current scope (External component).o Focus on SUT without worrying about its dependencies.

Page 11: Mocking with Moq

WHAT DOES A MOCKING FRAMEWORK DO?1. Create fake objects.2. Set behavior of fake objects.3. Verify method was called.4. And much more .

Page 12: Mocking with Moq

STEPS OF MOCKING

Arrange Act Assert

Page 13: Mocking with Moq

RULE OF THUMB

Apply mocks only on Unit Tests, not Integration Tests

Page 14: Mocking with Moq

TECHNICAL DETAILSo Mock objects have the same interface as the real objects they mimic, allowing a client object to remain unaware of whether it is using a real object or a mock object.o Many available mock object frameworks allow the programmer to specify which, and in what order, methods will be invoked on a mock object and what parameters will be passed to them, as well as what values will be returned.o Behavior of a complex object such as a network socket can be mimicked by a mock object, allowing the programmer to discover whether the object being tested responds appropriately to the wide variety of states such mock objects may be in.

Page 15: Mocking with Moq

HAND ROLLED MOCK Example

Page 16: Mocking with Moq

TRY IT | CUSTOMER SERVICEo This service dependent on:o CustomerAdressBuilder.o Has a method ‘From’ whose input parameter is a customer command and return an address as a

string.o CustomerRepository.o Can save a customer object on the persistence storage.

o Get mailing address to customer from CustomerAddressBuilder.o Throws InvalidCustomerMailingAddressException if mailing address is null.o Assign mailing address to customer.o Persist customer in CustomerRepository.

Page 17: Mocking with Moq

MOQ Code samples

Page 18: Mocking with Moq

2) SIMPLE MOCK – WATCH USING MOQo Create Single Customero Input : CustomerCreateCommand.o It has to:oCreate a customer object.o Persist it on the respository.

Page 19: Mocking with Moq

2) SIMPLE MOCK– TRY IToCreate Bulk of Customerso Input : List of CustomerCreateCommand.o It has to:oCreate a customer object.o Persist it on the respository.

Page 20: Mocking with Moq

3) RETURN VALUES – TRY IToNotes: oApply Moq on example of hand rolled mock.oICustomerAddressBuilder Interface.o string From(CustomerCreateCommand customercommand);

o Actions:o Mock address builder to return an Email.o Write a test method for testing exception if mailing address is null.o Verify that CustomerRepository Save method is called.

Page 21: Mocking with Moq

4) OUTPUT PARAMETERS – TRY IToNotes:oIMailingAddressFactory Interface.o bool TryParse(string mailingAddress, out MailingAddress result);

o Actions:o Mock IMailingAddressFactory to return an output parameter.o Set customer DetailedMailingAddress by the result.o Verify that CustomerRepository Save method is called.

Page 22: Mocking with Moq

5) MULTIPLE RETURN VALUES – TRY ITo Notes:oCheck IIdFactory Interface.oint Create();

o Create method of Customer Service has a list of Customer Create Commands.o Set a unique Id for each customer using IIdFactory Interface.o Persist it on the repository.o Actions:o Verify that CustomerRepository Save method is called.o Verify that Create method is called per command to set customer Id.

Page 23: Mocking with Moq

6) ARGUMENT TRACKING – TRY ITo Notes:o IFullNameFactory Interface.ostring From(string firstName, string lastName);

o Set Customer Fullname by result of From method in IFullNameFactory.o Persist it on the repository.o Actions:o Setup From in IFullNameFactory to get any string values in both input parameters.o Verify that both input parameters equals the command corresponding values.

Page 24: Mocking with Moq

7) EXECUTION FLOW – TRY ITNotes:o IStatusFactory Interface.o CustomerStatusEnum From(CustomerCreateCommand createCommand);

o CustomerStatusEnum (Normal, Platinum).o Set customer status by result from From method in IStatusFactory.o If Customer status is Platinum, use SaveSpecial in ICustomerRepository.o else, use Save in ICustomerRepository.Actions:o Setup From in IStatusFactory to return different results.o Verify that appropriate methods called.

Page 25: Mocking with Moq

8) PROPERTIES – TRY ITNotes:o Check ICustomerRepository Interface.o Check IApplicationSettings Interface.o Set Customer Repository Time Zone by Standard name of current time zone.

Actions:o Verify ICustomerRepository TimeZone setter.

Page 26: Mocking with Moq

8) PROPERTIES – TRY ITNotes:o Check ICustomerRepository Interface.o Check IApplicationSettings Interface.o Set WorkStationId of Customer by WorkStationId of IApplicationSettings.

Actions:o Verify IApplicationSettings WorkStationId getter.

Page 27: Mocking with Moq

8) PROPERTIES – TRY ITNotes:o Check ICustomerRepository Interface.o Check IApplicationSettings Interface.o Make it harder by using complex property object.Actions:o Verify getter of _applicationSettings.SystemConfiguration.AuditingInformation.WorkStationId.

Page 28: Mocking with Moq

8) PROPERTIES – TRY IT

1. Try using SetupProperty instead of Setup2. Try setup the property from the exposed object of

mock3. SetupAllProperties

Page 29: Mocking with Moq

9) EVENTS – TRY ITNotes:o Check IMailingRepository Interface.o CustomerRepository should subscribe to an Event NotifySalesTeam.o Once event is raised, it has to call NewCustomerMessage in IMailingRepository and pass the event argument.

Actions:o Verify that NewCustomerMessage is called if event raised.

Page 30: Mocking with Moq

MOQ | ADVANCED TOPICS Samples

Page 31: Mocking with Moq

1) RECURSIVE MOCKINGNotes:o Check IMailingAddressFactory Interface.o Get ICustomerAddressBuilder from IMailingAddressFactory .o Set Customer Mailing Address using From method in ICustomerAddressBuilder.

Actions:o Verify that From method in ICustomerAddressBuilder is called.

Page 32: Mocking with Moq

2) PROTECTED MEMBERSNotes:o Check CustomerNameFormatter class.

Actions:o Verify that RemoveUnderScoreFrom is called.

Page 33: Mocking with Moq

3) INTERFACESNotes:o Check StringSequenceReader class.

Actions:o Verify that Dispose method is called.

Page 34: Mocking with Moq

EDUWORX Real Example

Page 35: Mocking with Moq

BEST PRACTICES Hints on using TDD

Page 36: Mocking with Moq

THE BADo The use of mock objects can closely couple the unit tests to the actual implementation.o Test fails even though all mocked object methods still obey the contract of the previous implementation.o Over-use of mock objects as part of a suite of unit tests can result in a dramatic increase in the amount of maintenance.

Page 37: Mocking with Moq

THANK YOU!