【问题标题】:Is it possible to mock System.Windows.Window using moq是否可以使用 moq 模拟 System.Windows.Window
【发布时间】:2021-05-28 12:04:18
【问题描述】:

我有一个AsyncDelegateCommand,它采用Window 的参数,我尝试模拟类但我以异常The calling thread must be STA, because many UI components require this. 结束

删除门命令:

private AsyncDelegateCommand<Window> okCommand;

public AsyncDelegateCommand<Window> OkCommand => this.okCommand ?? (this.okCommand = new AsyncDelegateCommand<Window>(this.OkAsync));

方法实现:

private async Task OkAsync(Window win)
{
   //Logic
}

我目前嘲笑它的方式是使用:

private Mock<Window> mockWindow;
this.mockWindow = new Mock<Window>();
await this.sut.OkCommand.ExecuteAsync(this.mockWindow.Object);

在调试对象时,我可以将对象值视为异常this.mock Window.Object' threw an exception of type 'System.Reflection.TargetInvocationException

如果不可能,是否有替代方法来实现这一目标?

【问题讨论】:

  • 如果您使用的是 xUnit nuget.org/packages/Xunit.StaFact
  • @AthulRaj 我正在使用 nUnit
  • 为什么还要模拟一个窗口?我以为我们嘲笑了界面
  • @AthulRaj 如何在不模拟的情况下验证方法?我无法模拟 IWindowService 因为它是内部的。我想在方法上添加属性[Apartment(ApartmentState.STA)] 确实有效。

标签: c# wpf unit-testing nunit moq


【解决方案1】:

我能够通过在我的测试方法上添加 cmets [Apartment(ApartmentState.STA)] 中建议的属性来解决问题

例如:

[Test]
[Apartment(ApartmentState.STA)]
public async Task TestMethod()
{
    //Logic
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2011-06-13
    • 2019-09-11
    • 2010-11-16
    相关资源
    最近更新 更多