我正在学习如何做单元测试。我试图搜索如何对按钮单击事件进行测试,但找不到一个我能理解的答案。如何检查是否引发了TextBlock_MouseDown事件,并且随后是来自PostMethod的响应,该事件不能为null。我的问题是,我找不到一种方法,或者不知道如何使用NUnit检查TextBlock_MouseDown事件。
public partial class MainWindow : Window
{
public MainWindow(){
InitializeComponent();
}
public void TextBlock_MouseDown(object sender, MouseButtonEventArgs e){
//Check return value from PostMethod
string reponse = PostMethod("myurlhere");
}
public static String PostMethod(String val){
//Code
}
}
[TestFixture]
public class TestClass
{
[Test]
public void PostMethod_IsAlive_returnHello()
{
//ARRANGE
String url = "myurlhere";
//ACT
string response = MainWindow.PostMethod(url);
//ASSERT
Assert.AreEqual("\"Hello\"", response);
}
}发布于 2019-11-14 15:58:24
如果你想测试你的UI,你应该使用一个测试库来进行UI测试。例如FlaUI (https://github.com/Roemer/FlaUI)。
NUnit是用来测试你的代码的。例如,如果您想检查PostMethod()是否返回特定值。
如果您只想检查PostMethod()的结果,可以将method外包给另一个class并对其进行测试(MainWindow现在将在其代码中使用)。
外包类
public class OutsourcedClass
{
public string PostMethod(string url)
{
return url;
}
}单元测试
public class OutsourcedClassTest
{
private OutsourcedClass _Instance;
[SetUp]
public void Setup()
{
_Instance = new OutsourcedClass();
}
[Test]
public void PostMethodTest()
{
string url = "foo";
Assert.AreEqual(url, _Instance.PostMethod(url));
}
}https://stackoverflow.com/questions/58851763
复制相似问题