【发布时间】:2023-03-29 22:46:01
【问题描述】:
单元测试新手。我有一个 WPF 客户端应用程序通过 basicHttpbinding 连接到 WCF 服务。一切都很好。我在我的视图模型中使用简单的构造函数依赖注入,传入一个IServiceChannel,然后我将其称为服务方法,例如:
IMyserviceChannel = MyService;
public MyViewModel(IMyServiceChannel myService)
{
this.MyService = myService;
}
Private void GetPerson()
{
var selectedPerson = MyService.GetSelectedPerson();
}
然后我在客户端应用程序中添加了一个 MS 测试项目,我正在尝试使用 Moq 来模拟我的服务:
[TestMethod]
public void GetArticleBody_Test_Valid()
{
// Create channel mock
Mock<IIsesServiceChannel> channelMock = new Mock<IIsesServiceChannel>(MockBehavior.Strict);
// setup the mock to expect the Reverse method to be called
channelMock.Setup(c => c.GetArticleBody(1010000008)).Returns("110,956 bo/d, 1.42 Bcfg/d and 4,900 bc/d. ");
// create string helper and invoke the Reverse method
ArticleDataGridViewModel articleDataGridViewModel = new ArticleDataGridViewModel(channelMock.Object);
string result = channelMock.GetArticleBody(1010000008);
//Assert.AreEqual("cba", result);
//verify that the method was called on the mock
channelMock.Verify(c => c.GetArticleBody(1010000008), Times.Once());
}
测试在此处的方法调用处以 System.NullReferenceException. Object reference not set to an instance of an object. 失败:
string result = articleDataGridViewModel.IsesService.GetArticleBody(1010000008);
所以我在徘徊这是否是最好的方法还是我最好以某种方式模拟适用于测试的 viewModel 的孤立部分?
【问题讨论】:
-
“异常被进一步捕获到视图模型中”是什么意思?
-
抱歉,问题已编辑。我在测试中的方法调用上得到“对象引用未设置为对象的实例”。我刚刚新建了一个 viewModel 对象。显然,对象的所有成员都持有空值,因为我没有从构造函数初始化它们中的任何一个,但不确定为什么会抛出这个异常?
-
您的视图模型代码**在哪里?
-
在问题中。我包括了手头的构造函数和方法
标签: c# wpf wcf unit-testing moq