Click here to Skip to main content
15,117,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am learning Test Driven Development and trying to use Moq library for mocking. What is the purpose of Setup method of Mock class?
Posted

1 solution

Somewhere in the code, methods or properties of the mocked object will be accessed. What is the mocked object expected to do then? The Setup methods are used for that purpose: they tell the mocked object what to do here.
Example: I have an object with a property, and the code will call the property get.
C#
Mock<ISessionConfig> theConfig = new Mock<ISessionConfig>();
string customerToken = Guid.NewGuid().ToString();
theConfig.SetupGet(m => m.CustomerToken).Returns(customerToken);
ClassToBeTested test = new ClassToBeTested(theConfig.Object);

I create a mock for the corresponding interface, tell it that it has to return customerToken when its CustomerToken property is called, and then inject the mock into the class to be tested. Somewhere in the constructor of ClassToBeTested (or in a method called later in the test), the CustomerToken of the mocked object is required, and will return the value from the setup.
More methods exist for method calls, also for property set.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900