【发布时间】:2014-05-29 12:53:32
【问题描述】:
我已经安装了 com0com,以便我可以编写 NUnit 测试。以防万一键盘楔的定义不同,它的简要描述是一个软件,它监听串行通信设备,读取发送给它的任何数据(在我的情况下将其格式化为 ASCII 数据)然后将其发送到虚拟键盘。此代码在生产中确实有效,但我们现在需要记录我们的代码或进行单元测试以证明它应该如何使用。所以这是我的测试
[Test()]
public void WedgeSendsTextToVirtualKeyboardTest()
{
(var form = new Form())
using(var sp = new System.IO.Ports.SerialPort("COM"+COMB, 115200))
using (var wedge = new KeyboardWedgeConfiguration(WEDGE_KEY))
{
sp.Open();
TextBox tb = SetupForm(form);
TurnOnKeyboardWedge(wedge);
form.Activate();
form.Activated += (s, e) =>
{
tb.Focus();
};
while (!tb.Focused) { }
string str = "Hello World";
sp.Write(str);
//wait 1 second. This allows data to send, and pool in the wedge
//the minimum wait time is 200ms. the string then gets put into bytes
//and shipped off to a virtual keyboard where all the keys are pressed.
System.Threading.Thread.Sleep(1000);
Expect(tb.Text, Is.EqualTo(str));
}
}
private static TextBox SetupForm(Form form)
{
TextBox tb = new TextBox();
tb.Name = "tb";
tb.TabIndex = 0;
tb.AcceptsReturn = true;
tb.AcceptsTab = true;
tb.Dock = DockStyle.Fill;
form.Controls.Add(tb);
form.Show();
return tb;
}
private static void TurnOnKeyboardWedge(KeyboardWedgeConfiguration wedge)
{
wedge.Port = COMA;
wedge.PortForwardingEnabled = true;
wedge.Baud = 115200;
System.IO.Ports.SerialPort serialPort;
wedge.StartRerouting();
Assert.IsTrue(wedge.IsAlive(out serialPort));
Assert.IsNotNull(serialPort);
}
当测试运行时,表单显示,文本框中没有文本,然后测试退出,最后一个断言失败 (Expect(tb.Text, Is.EqualTo(str));) 说 tb.Text 是 string.Empty。我尝试了许多不同的策略来关注该文本框(我假设这至少是问题所在)。有一次我让我的睡眠时间更长,以便我有时间点击文本框并输入自己,但我无法点击该框(我假设这是因为睡眠操作......这也可能是为什么我的楔子也不能在那里输入)所以我该如何解决这个问题并让我的测试通过。这段代码再次在生产环境中工作,所以我 100% 确信这是我的测试(可能是睡眠操作)
【问题讨论】:
-
我认为this question/answer 可以帮助指导您。您可以做类似的事情,将表单移动到它自己的线程,并将串行端口写入另一个线程,然后等待它们。