Search code examples
c#visual-studiounit-testingintegration-testing

How to unit test methods in windows form class?


I have a developing a c# windows form application and I have a method that exists inside the main form class.

Imagine methodA as part of the main form class.

public void methodA() {
    A.someMethod();
    B.someMethod();

    // some more code

    if (someCondition) {
        // execute some code 
    }

    // initialize timer and set event handler for timer
    // run new thread 

    }

class A {
    someMethod() {...}
}

class B {
    someMethod() {...}
}

How would I run tests to test the branch logic of this methodA (isCondition)? since it involves initializing timer and running threads. Can i only verify the logic while doing system test ? I dont think it is possible to mock the timer and threading function.

Thank you !


Solution

  • Of course you can mock the timer. This is by creating a new interface, say, ITimerWrapper and implement it by using the concrete Timer class. Basically a wrapper of the Timer class. Then use that instead of the concrete Timer class you have.

    Something in the tune of:

    public partial class Form1 : Form
    {
        private readonly ITimerWrapper _timerWrapper;
        public Form1(ITimerWrapper timerWrapper)
        {
            InitializeComponent();
    
            this._timerWrapper = timerWrapper; // of course this is done via dependency injection
            this._timerWrapper.Interval = 1000;
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            // now you can mock this interface
    
            this._timerWrapper.AddTickHandler(this.Tick_Event);
            this._timerWrapper.Start();
        }
    
        private void Tick_Event(object sender, EventArgs e)
        {
            Console.WriteLine("tick tock");
        }
    }
    
    public interface ITimerWrapper
    {
        void AddTickHandler(EventHandler eventHandler);
        void Start();
        void Stop();
        int Interval { get; set; }
    }
    public class TimerWrapper : ITimerWrapper
    {
        private readonly Timer _timer;
    
        public TimerWrapper()
        {
            this._timer = new Timer();
        }
    
        public int Interval
        {
            get
            {
                return this._timer.Interval;
            }
            set
            {
                this._timer.Interval = value;
            }
        }
    
        public void AddTickHandler(EventHandler eventHandler)
        {
            this._timer.Tick += eventHandler;
        }
    
        public void Start()
        {
            this._timer.Start();
        }
    
        public void Stop()
        {
            this._timer.Stop();
        }
    }
    

    Then for the spinning of a new thread, that's also testable by doing the same thing.

    Bottomline is to have an interface to separate concerns and mock the interface on your unit test.