The usual solution for this would be to mock the MessageBox
class and simulate what the Show
method returns. Since it's a static method, it requires additional work and some modifications in your code. Here's a possible solution:
Create a class that encapsulates the Show
method:
public class MyMessageBox {
public virtual DialogResult Show(string text, string caption, MessageBoxButtons buttons) {
return MessageBox.Show(text, caption, buttons);
}
}
Then modify your code to use that class:
class Abc {
internal int a;
private readonly MyMessageBox messageBox;
public Abc(MyMessageBox messageBox) {
this.messageBox = messageBox;
}
public void MyMethod() {
if (messageBox.Show("Sure?", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)
a = 1;
else
a = 0;
}
}
After that, you can write tests that mock the MyMessageBox
class. I'm using NSubstitute in the example below:
[Test]
public void Test() {
MyMessageBox messageBox = Substitute.For<MyMessageBox>();
messageBox.Show("Sure?", "Title", MessageBoxButtons.YesNo).Returns(DialogResult.Yes);
Abc abc = new Abc(messageBox);
abc.MyMethod();
Assert.AreEqual(1, abc.a);
}
That's one way to do it. It's up to you to decide if it's worth the effort or not.