gpt4 book ai didi

c# - 单元测试 COM 事件?

转载 作者:太空狗 更新时间:2023-10-29 20:40:19 25 4
gpt4 key购买 nike

我们有一个用 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();

我用谷歌搜索并在 StackOverflow 上阅读了类似的问题。我已经尝试了所有建议的方法,但无法正常工作!

到目前为止,我已尝试使用 active dispatcher 运行我的测试但没有成功。我还尝试使用 Dispatcher.PushFrame() 在主线程中手动发送消息。没有。我的事件永远不会触发。我创建了一个简单的 WinForms 项目并验证了我的事件在正常设置中工作。因此,此问题仅适用于单元测试。

问:如何进行可以成功触发事件事件处理程序的常规 C# 单元测试?

有人应该有一个工作样本!请帮忙。

最佳答案

如果您的 COM 对象是一个 STA 对象,您可能需要运行一个消息循环来触发它的事件。

您可以在 ApplicationForm 对象周围使用一个小包装来做到这一点。这是我在几分钟内写的一个小例子。

请注意,我没有运行或测试它,因此它可能无法正常工作,清理工作应该会更好。但它可能会为您提供解决方案的方向。

使用这种方法,测试类看起来像这样:

[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));
}

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();
}
}

这有帮助吗?

关于c# - 单元测试 COM 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com