【问题标题】:Get return value of invoked method in UnitTest using Moq使用 Moq 在 UnitTest 中获取调用方法的返回值
【发布时间】:2021-03-16 20:57:58
【问题描述】:

我正在使用 Moq 进行单元测试。在我尝试进行单元测试的方法中,我试图确保它不会引发异常,但我还想获取我正在单元测试的方法的返回值以验证结果。

_myService.Invoking(x => x.TestMethod(request)).Should().NotThrow();

以上工作。测试通过。但是,我想得到TestMethod的返回值。

【问题讨论】:

标签: c# unit-testing moq xunit


【解决方案1】:

事情就是这样,试着测试你想要得到的,而不是你不想要的:

不好(确保我们没有异常):

_myService.Invoking(x => x.TestMethod(request)).Should().NotThrow();

好(确保我们得到我们想要的):

var result = _myService.TestMethod(request);
// whatever asserts you want to perform on `result`
// e.g.
// Assert.IsNotNull(result);
// Assert.IsTrue(result.Count == 2);
// Assert.AreEqual(result[0],"Foo");
// etc.

【讨论】:

    【解决方案2】:

    如果方法返回你期望它返回的值,则自动表示该方法没有抛出异常。

    另一方面,如果抛出异常,则不会有返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      相关资源
      最近更新 更多