Home > Back-end >  How to unit test private Windows Forms?
How to unit test private Windows Forms?

Time:10-29

I'm a beginner at unit testing and I am currently confronted with my 1st problem.

I want to unit test my CheckedChange function:

protected void rbtnMSSQL_CheckedChanged(object sender, EventArgs e)
{
    if (rbtnMSSQL.Checked && rbtnOracle.Checked)
    {
        rbtnOracle.Checked = false;
    }
}

Well, if Iwant to assert, I need the bool value from rbtnMSSQL.Checked and rbtnOracle.Checked, but they are private.

I guess it would work with internal and

[assembly: InternalsVisibleTo("UnitTests")]

but is it a good approach to chance every private value to an internal value?

CodePudding user response:

Something that is private is used to make things works inside the class.

What unit tests should assert is how class works, if it returns correct values, etc.

Ulitmately, setting values to checkboxes should be done by some controller or view model (if you used correct design pattern), and this setting correct value would be then public (to be visible by view). So then it could be unit tested.

So, maybe not the answer you are looking for, but you need to redesign parts of your code or entire view (splitting to view and viewmodel).

CodePudding user response:

It is difficult to unit test functions that have side-effects. Usually, you should only create unit tests for functions that are free of side-effects. For that, extract the actual functionality from the event handler and call it from the event handler:

protected void rbtnMSSQL_CheckedChanged(object sender, EventArgs e)
{
    DisableOtherCheckBoxWhenOneWasChecked(rbtnMSSQL, rbtnOracle);
}

// Actually put that function in a separate class.
public void DisableOtherCheckBoxWhenOneWasChecked(CheckBox checkedChanged, CheckBox other)
{
    if (checkedChanged.Checked && other.Checked)
    {
        other.Checked = false;
    }
}

Now you can write a unit test for DisableOtherCheckBoxWhenOneWasChecked and pass in your own CheckBox objects.

In general, unit tests aren't such a good tool to test UI stuff. There are specific test frameworks for UI tests that you should look at.

  • Related