Ben
Ben

Reputation: 2269

How can I test if a control is focused in C# Windows Forms?

    /// <summary>
    ///Tests the reset form button
    ///</summary>
    [TestMethod()]
    public void frmResetLinkTestNo()
    {
        frmQuote_Accessor target = new frmQuote_Accessor();
        AutomotiveManager_Accessor._isBeingTested = true;
        AutomotiveManager_Accessor._messageBoxResult = DialogResult.No;

        target.txtVehicleSalesPrice.Text = "1000";

        object sender = null;
        EventArgs e = new EventArgs();

        target.lnkReset_Click(sender, e);
        // This assert fails
        Assert.AreEqual(true, target.txtVehicleSalesPrice.Focused);
        Assert.AreEqual("1000", target.txtVehicleSalesPrice.SelectedText);
    }

The method call target.lnkReset_Click(sender, e) triggers an event handler that shows a dialog box returning a YES or NO result. If the user presses YES or NO the first text box element of the form called txtVehicleSalesPrice is focused. This functionality works when I test it manually, but I cannot get accurate results if the element is focused. The second assert checking if the text is selected works.

What do I need to do for the unit test to be able to check if a form element is focused?

Upvotes: 2

Views: 6888

Answers (2)

gretro
gretro

Reputation: 2009

Well, I'd say you would need to mock the dialog for 'YES' and 'NO'. With this mock, you could force the form to behave the way you want it to. And then check that the field is indeed focused.

You can simply get the Dialog to be built in the constructor and set it in a public property, or you could create a mockable Factory of IYesNoDialog to produce more than one. The best way to do this is to abstract the form with an interface, like in the following example.

public interface IYesNoDialog {
    // DialogResult, I guess...
    // Whatever methods you need here to open the Dialog and control it.
}

public class YesNoDialog: Form, IYesNoDialog {
    //Implementation of the dialog here...
}

public class WhateverForm: Form {
    public IYesNoDialog YesNoDialog { get; set;}

    public WhateverForm() {
        this.YesNoDialog = new YesNoDialog();
    }
}

** Sorry if I misused the base types. My WinForms background is pretty far, but the concept remains the same.

Upvotes: -2

Gargen Hans
Gargen Hans

Reputation: 90

I didn't get exactly what you mean. But if you want to check if a control ( Button1 for example ) is focused. you can use this :

if (Button1.Focused){
    MessageBox.Show("The button is focused");
}

Upvotes: 4

Related Questions