Junior — Middle
Can you give an example of conducting unit testing for a graphical user interface?
sobes.tech AI
Answer from AI
For unit testing graphical user interfaces (GUI) in C#, frameworks are often used that allow simulating user interaction with interface elements and checking their behavior.
An example using NUnit and the NUnit.Forms library for testing Windows Forms:
using NUnit.Framework;
using NUnit.Extensions.Forms;
public class MyFormTests : NUnitFormTest
{
private MyForm form;
[SetUp]
public void SetUp()
{
form = new MyForm();
form.Show();
}
[TearDown]
public void TearDown()
{
form.Close();
}
[Test]
public void ButtonClick_ShouldChangeLabelText()
{
// Find button by name
ButtonTester button = new ButtonTester("myButton", form);
LabelTester label = new LabelTester("myLabel", form);
// Check initial text
Assert.AreEqual("Initial text", label.Text);
// Click the button
button.Click();
// Check that the text has changed
Assert.AreEqual("Text after click", label.Text);
}
}
In this example, we create a form, simulate a click on a button, and check the change in label text. This approach allows testing interaction logic in the UI without manual testing.