Unit Testing and Mocking using MOQ

Post on 11-May-2015

615 views 1 download

Tags:

description

A brief description of unit testing, with a more thorough walkthrough of how to mock using MOQ. The demo code can be found at http://1drv.ms/1kQJWhb

Transcript of Unit Testing and Mocking using MOQ

MockingMaking Writing Unit Tests Your Favorite

Thing to Do

Unit Testing

Your Code

Test

Test

Test

What is Being Unit Tested?• Classes or other component • Public methods• Other methods• Occasionally

• We will refer to the unit as the System Under Test or SUT

The Big Three Requirements• Tests are readable • Tests are trustworthy• Tests are maintainable

Structure of a Unit Test[TestMethod]public void Method_Scenario_Result(){

// Set dependencies, build SUT, set // expectations

// Exercise the SUT

// Check behaviour/state of SUT

// Check that expectations have been met}

Assert

Act

Arrange

Structure of a Unit Test[TestMethod]public void Method_Scenario_Result(){

// Set dependencies, build SUT, set // expectations

// Exercise the SUT

// Check behaviour/state of SUT

// Check that expectations have been met}

Assert

Act

Arrange

No Logic

Tests Should Have No Logic

• No switches, ifs or cases• Only arrange, act, assert

• Test logic == test bugs

[Test]public void CreateNumString_TwoSimpleNumbers_ReturnsStringWithCommaBetween(){ StringCalc sc = new StringCalc(); string result = sc.CreateNumString(1, 2); Assert.AreEqual(String.Format("{0},{1}", x, y), result);}

What is NOT a Unit Test• Tests that require additional, external set up in order

to be run• These are really integration tests

• Tests that require end-to-end functionality• These are really functional tests

Assertions Types• State verification• Method changes SUT state

• Behaviour verification• Verify calls between SUT and collaborator

What do the tests depend on?

• Collaborators• Anything called from the System Under Test

SUT DependancyDependancy

Dependency

Dependency Injection• A 25-dollar term for a 5-cent concept. • Dependency injection means giving an object its

instance variables. • Via James Shore

public class Sample{   private DatabaseThingie myDatabase;

  public Sample() {     myDatabase = new DatabaseThingie();   }

  public void DoStuff() {     myDatabase.GetData();   } }

How do we give these instances?

• Constructor injection• Property Injection (setter injection)• Method Injection• Service Locator• Interception framework

Fake it so – Different Kinds of Helpers• Stub – just shut up and help me• minimal behavior

• Mock – tell me when I make a mistake• able to set expectations

• Fake – behave like the real thing, more or less• simplified implementation

• Spy – tell me what happened• record calls

A simple Mocking Example

Expecting Exceptions

Verifying that Calls Were Made

Conditional Mocking

Callbacks

Testing Exceptions