Mocking with Moq

Post on 11-Feb-2017

501 Views

Category:

Software

0 Downloads

Preview:

Click to see full reader

Transcript

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

YOUR EXPECTATIONS

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?

TEST DRIVEN DEVELOPMENT

THE PROBLEM

SOLUTION

INTRODUCTION What is mocking?

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.

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.

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.

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 .

STEPS OF MOCKING

Arrange Act Assert

RULE OF THUMB

Apply mocks only on Unit Tests, not Integration Tests

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.

HAND ROLLED MOCK Example

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.

MOQ Code samples

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

8) PROPERTIES – TRY IT

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

mock3. SetupAllProperties

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.

MOQ | ADVANCED TOPICS Samples

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.

2) PROTECTED MEMBERSNotes:o Check CustomerNameFormatter class.

Actions:o Verify that RemoveUnderScoreFrom is called.

3) INTERFACESNotes:o Check StringSequenceReader class.

Actions:o Verify that Dispose method is called.

EDUWORX Real Example

BEST PRACTICES Hints on using TDD

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.

THANK YOU!

top related