l33*_*33t 7 c# com unit-testing dispatcher event-handling
我们有一个用C++编写的自制COM组件.我们现在想在C#测试项目中测试它的功能和事件.功能测试非常简单.但是,事件永远不会被触发.
MyLib.MyClass m = new MyLib.MyClass();
Assert.IsTrue(m.doStuff()); // Works
// This does not work. OnMyEvent is never called!
m.MyEvent += new MyLib.IMyClassEvents_MyEventHandler(OnMyEvent);
m.triggerEvent();
Run Code Online (Sandbox Code Playgroud)
我已经在Google上搜索了这个并在StackOverflow上阅读了类似的问题.我已经尝试了所有提出的方法,但无法使其正常工作!
到目前为止,我已经尝试使用主动调度员运行我的测试,但没有成功.我也尝试使用在主线程中手动泵送消息Dispatcher.PushFrame().没有.我的事件永远不会触发 我创建了一个简单的WinForms项目并验证我的事件在正常设置中工作.因此,此问题仅适用于单元测试.
问:如何进行可以成功触发活动事件处理程序的常规C#单元测试?
那里的人应该有一份工作样本!请帮忙.
如果您的 COM 对象是 STA 对象,您可能需要运行消息循环才能触发其事件。
Application您可以使用和对象周围的小包装Form来做到这一点。这是我在几分钟内写的一个小例子。
请注意,我没有运行或测试它,因此它可能不起作用,并且清理可能会更好。但它可能会为您提供解决方案的方向。
使用这种方法,测试类将如下所示:
[TestMethod]
public void Test()
{
MessageLoopTestRunner.Run(
// the logic of the test that should run on top of a message loop
runner =>
{
var myObject = new ComObject();
myObject.MyEvent += (source, args) =>
{
Assert.AreEqual(5, args.Value);
// tell the runner we don't need the message loop anymore
runner.Finish();
};
myObject.TriggerEvent(5);
},
// timeout to terminate message loop if test doesn't finish
TimeSpan.FromSeconds(3));
}
Run Code Online (Sandbox Code Playgroud)
代码如下MessageLoopTestRunner:
public interface IMessageLoopTestRunner
{
void Finish();
}
public class MessageLoopTestRunner : Form, IMessageLoopTestRunner
{
public static void Run(Action<IMessageLoopTestRunner> test, TimeSpan timeout)
{
Application.Run(new MessageLoopTestRunner(test, timeout));
}
private readonly Action<IMessageLoopTestRunner> test;
private readonly Timer timeoutTimer;
private MessageLoopTestRunner(Action<IMessageLoopTestRunner> test, TimeSpan timeout)
{
this.test = test;
this.timeoutTimer = new Timer
{
Interval = (int)timeout.TotalMilliseconds,
Enabled = true
};
this.timeoutTimer.Tick += delegate { this.Timeout(); };
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// queue execution of the test on the message queue
this.BeginInvoke(new MethodInvoker(() => this.test(this)));
}
private void Timeout()
{
this.Finish();
throw new Exception("Test timed out.");
}
public void Finish()
{
this.timeoutTimer.Dispose();
this.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
这有帮助吗?
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |