Search code examples
c#unit-testingvisual-studio-2010vs-unit-testing-framework

First Unit Test (VS2010 C#)


This is my first encounter with unit testing and I am trying to understand how can this concept be used on a simple date validation.

The user can select a ToDate that represents the date until a payment can be made. If our date is not valid the payment cant be made.

    private void CheckToDate(DateTime ToDate)
    {
        if (Manager.MaxToDate < ToDate.Year)
            //show a custom message
    }

How can unit tests be used in this case?

Regards,

Alex

Thanks for your answers:

As suggested by many of you I will split the function and separate the validation from the message display and use unit tests just for this.

public bool IsDateValid(DateTime toDate)
{
    return (Manager.MaxToDate < toDate.Year);
}

Solution

  • Yes it is possible. But unit testing changes design of your class. To make possible unit testing of this code, you should made following changes:

    1. Make your method public. (It is possible to make it protected, but for simplicity make it public).

    2. Extract all external dependencies of this method to interface, so you can mock them. Then you can use some mocking library (moq, Rhino.Mocks) to simulate real dependencies and write asserts.

    3. Write test.

    Here is sample code.

    The class under test:

    public class ClassUnderTest
    {
        public IManager Manager {get;set;}
        public IMessanger Messanger {get;set}
    
        public  ClassUnderTest (IManager manager, IMessanger messanger)
        {
            Manager = manager;
            Messanger = messanger;
        }
    
        private void CheckToDate(DateTime ToDate)
        {
            if (Manager.MaxToDate < ToDate.Year)
                //show a custom message
                Messanger.ShowMessage('message');
        }
    }
    

    Test:

    [TestFixture]
    public class Tester
    {
        public void MessageIsShownWhenDateIsLowerThanMaxDate()
        {
            //SetUp
            var manager = new Mock<IManager>();
            var messanger = new Mock<IMessanger>();
    
            var maxDate = DateTime.Now;
    
            manager.Setup(m => m.MaxToDate).Returns(maxDate);
    
            var cut = new ClassUnderTest (manager.Object, messanger.Object);
    
            //Act
            cut.CheckToDate();
    
            //Assert
            messanger.Verify(foo => foo.ShowMessage("message"), Times.AtLeastOnce())
        }
    }
    

    Design change, introduced by test gives you nice decoupling in system. And tests could be written for specific classes, when external dependencies are event not written.