Click here to Skip to main content
15,879,096 members
Articles / Programming Languages / C#

From Mocks to Isolation

Rate me:
Please Sign up or sign in to vote.
4.97/5 (19 votes)
31 Oct 2008CPOL16 min read 48.9K   94   50  
The article discusses how to isolate the code under test from behavior of referenced classes by using mocking frameworks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NUnit.Framework;

using TypeMock;

using Customers;

namespace UnitTests
{
    [TestFixture]
    public class CarInsuranceTest2_NaturalMocks
    {
        [Test]
        [VerifyMocks]
        public void GetCustomerPriceGroup_Adult_UnableToConnect()
        {
            Customer customer = MockManager.MockObject<Customer>().Object;
            customer.DateOfBirth = new DateTime(1970, 1, 1, 0, 0, 0);

            using (RecordExpectations recorder = new RecordExpectations())
            {
                var dataLayer = new DataLayer();
                recorder.ExpectAndReturn(dataLayer.GetCustomer(0), customer);
            }

            var carInsurance = new CarInsurance();
            PriceGroup priceGroup = carInsurance.GetCustomerPriceGroup(0);
            Assert.AreEqual(PriceGroup.Adult, priceGroup, "Incorrect price group");
        }

        [Test]
        [VerifyMocks]
        public void GetCustomerPriceGroup_Adult()
        {
            Customer customer = MockManager.MockObject<Customer>().Object;
            customer.DateOfBirth = new DateTime(1970, 1, 1, 0, 0, 0);

            using (RecordExpectations recorder = new RecordExpectations())
            {
                var dataLayer = new DataLayer();
                dataLayer.OpenConnection();
                recorder.ExpectAndReturn(dataLayer.GetCustomer(0), customer);
                dataLayer.CloseConnection();
            }

            var carInsurance = new CarInsurance();
            PriceGroup priceGroup = carInsurance.GetCustomerPriceGroup(0);
            Assert.AreEqual(PriceGroup.Adult, priceGroup, "Incorrect price group");
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Architect Miles AS
Norway Norway
Vagif Abilov is a Russian/Norwegian software developer and architect working for Miles. He has more than twenty years of programming experience that includes various programming languages, currently using mostly C# and F#.

Vagif writes articles and speaks at user group sessions and conferences. He is a contributor and maintainer of several open source projects, including Simple.Data OData adapter, Simple.OData.Client and MongOData.

Comments and Discussions