如何验证使用 Moq 仅调用了一次方法?

编程入门 行业动态 更新时间:2024-10-28 17:15:58
本文介绍了如何验证使用 Moq 仅调用了一次方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何验证使用 Moq 的方法只调用了一次?Verify() 与 Verifable() 的事情确实令人困惑.

解决方案

你可以使用Times.Once(),或者Times.Exactly(1):p>

mockContext.Verify(x => x.SaveChanges(), Times.Once());mockContext.Verify(x => x.SaveChanges(), Times.Exactly(1));

以下是 Times 类的方法:p>

  • AtLeast - 指定模拟方法的调用次数最少.
  • AtLeastOnce - 指定至少应调用一次模拟方法.
  • AtMost - 指定模拟方法的调用次数最多.
  • AtMostOnce - 指定一个模拟的方法最多应该被调用一次.
  • Between - 指定应在 from 和 to 时间之间调用模拟方法.
  • Exactly - 指定一个模拟方法应该被准确地调用几次.
  • Never - 指定不应调用模拟方法.
  • Once - 指定一个模拟方法应该被调用一次.

记住它们是方法调用;我一直被绊倒,以为它们是属性而忘记了括号.

How do I verify a method was called exactly once with Moq? The Verify() vs. Verifable() thing is really confusing.

解决方案

You can use Times.Once(), or Times.Exactly(1):

mockContext.Verify(x => x.SaveChanges(), Times.Once()); mockContext.Verify(x => x.SaveChanges(), Times.Exactly(1));

Here are the methods on the Times class:

  • AtLeast - Specifies that a mocked method should be invoked times times as minimum.
  • AtLeastOnce - Specifies that a mocked method should be invoked one time as minimum.
  • AtMost - Specifies that a mocked method should be invoked times time as maximum.
  • AtMostOnce - Specifies that a mocked method should be invoked one time as maximum.
  • Between - Specifies that a mocked method should be invoked between from and to times.
  • Exactly - Specifies that a mocked method should be invoked exactly times times.
  • Never - Specifies that a mocked method should not be invoked.
  • Once - Specifies that a mocked method should be invoked exactly one time.

Just remember that they are method calls; I kept getting tripped up, thinking they were properties and forgetting the parentheses.

更多推荐

如何验证使用 Moq 仅调用了一次方法?

本文发布于:2023-11-15 00:29:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1589515.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Moq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!