Providing a solution would be much easier with the UI method or related methods posted. Also seeing the TestMethod(s) could help even incomplete methods.
If I understand your test purpose is to determine what happens on the different click possibilities?
You could set up your actual method that triggers the MessageBox
using Inversion of Control and Dependency Injection like this:
public class ClassUnderTest
{
private static Func<string, string, MessageBoxButtons, DialogResult>
_messageBoxLocator = MessageBox.Show;
public static Func<string, string, MessageBoxButtons, DialogResult>
MessageBoxDependency
{
get { return _messageBoxLocator; }
set { _messageBoxLocator = value; }
}
private void MyMethodOld(object sender, EventArgs e)
{
if (MessageBox.Show("test", "", MessageBoxButtons.YesNo) ==
System.Windows.Forms.DialogResult.Yes)
{
//Yes code
AnsweredYes = true;
}
else
{
//No code
}
}
public bool AnsweredYes = false;
public void MyMethod(object sender, EventArgs e)
{
if (MessageBoxDependency(
"testText", "testCaption", MessageBoxButtons.YesNo)
==
System.Windows.Forms.DialogResult.Yes)
{
//proceed code
AnsweredYes = true;
}
else
{
//abort code
}
}
}
and then the test method (remember to include the using Microsoft.VisualStudio.TestTools.UnitTesting;
at the top) would be like this:
[TestMethod]
public void ClassUnderTest_DefaultAnsweredYes_IsFalse()
{
var classUnderTest = new ClassUnderTest();
Assert.AreEqual(false, classUnderTest.AnsweredYes);
}
[TestMethod]
public void MyMethod_UserAnswersYes_AnsweredYesIsTrue()
{
//Test Setup
Func<string, string, MessageBoxButtons, DialogResult>
fakeMessageBoxfunction =
(text, caption, buttons) =>
DialogResult.Yes;
//Create an instance of the class you are testing
var classUnderTest = new Testing.ClassUnderTest();
var oldDependency = Testing.ClassUnderTest.MessageBoxDependency;
Testing.ClassUnderTest.MessageBoxDependency = fakeMessageBoxfunction;
try
{
classUnderTest.MyMethod(null, null);
Assert.AreEqual(true, classUnderTest.AnsweredYes);
//Assert What are you trying to test?
}
finally
{ //Ensure that future tests are in the default state
Testing.ClassUnderTest.MessageBoxDependency = oldDependency;
}
}