[英]Moq testing if method1 calls second method2 in same class
I'm new to Moq 我是Moq的新手
I read a lot about Moq
testing and that you shouldn't test your mock object, instead you should use Moq to stub dependencies and make it to act like you want to. 我了解了很多有关
Moq
测试的知识,并且您不应该测试自己的模拟对象,而应该使用Moq来对依赖项进行存根并使其表现为所需的行为。 But now I am asking myself, how can you test if a method be called from another method in the same class, like this code: 但是现在我问自己,如何测试是否从同一类的另一个方法中调用一个方法,例如以下代码:
public class A // --> class i want to test
{
public virtual void TestMethod() // --> does it call testmethod2
{
TestMethod2();
}
public virtual void TestMethod2()
{
// Do something
}
}
I thought I can write the Unittest like this: 我以为我可以这样写单元测试:
[TestMethod]
public void MyTestMethod()
{
Mock<A> aMock = new Mock<A>();
aMock.Verify(o => o.TestMethod2(), Times.Once);
aMock.TestMethod();
aMock.VerifyAll();
}
But is this valid? 但这有效吗? Thank you for all good answers!
感谢您的所有好的答案!
Moq is only able to mock out methods which are virtual (or provide mock implementations for interfaces). Moq仅能模拟出虚拟方法(或为接口提供模拟实现)。 If you try a
Setup
or Verify
on a non-virtual member, you'll get the error 如果您尝试在非虚拟成员上进行
Setup
或Verify
,则会收到错误消息
Invalid verify on a non-virtual member: m => m.TestMethod2()
对非虚拟成员的无效验证:m => m.TestMethod2()
In your case, you would need to change TestMethod2
to virtual, ie 在您的情况下,您需要将
TestMethod2
更改为virtual,即
public virtual void TestMethod2()
Which can then be tested: 然后可以对其进行测试:
var aMock = new Mock<A>();
aMock.Object.TestMethod();
aMock.Verify(m => m.TestMethod2(), Times.Once);
As you've suggested, testing whether a class calls methods internal to itself is a smell, indication that you're either 如您所建议,测试类是否在其内部调用方法是一种气味,表明您是
TestMethod2()
was private, it's none of our business to even know about it). TestMethod2()
是私有的,那么甚至不知道它也不关我们的事)。 Note 注意
Verify
a call before you've invoked the method on the SUT that you want to test, ie move the Verify
to after the invocation of .TestMethod()
as I've done. Verify
调用,即,在我完成.TestMethod()
调用之后,将Verify
移至。 Setup
+ VerifyAll
approach to testing, ie ensuring that everything you've setup is actually invoked: Setup
+ VerifyAll
方法进行测试,即确保已实际调用您设置的所有内容: aMock.Setup(m => m.TestMethod2());
aMock.Object.TestMethod();
aMock.VerifyAll();
There is however debate around whether the usage of VerifyAll
violates AAA
principals (since you're also in effect specifying the Verify
criteria in the Arrange
piece), and I've also found that this approach makes it impossible to refactor and DRY up Mock setups in large scale tests, and you also lose some of the finer level of checking (eg Times.Once
). 但是,关于
VerifyAll
的使用是否违反AAA
原则存在VerifyAll
(因为您实际上还在Arrange
部分中指定了Verify
条件),而且我还发现,这种方法无法重构和干燥Mock设置。在大规模测试中,您还会失去一些更好的检查级别(例如Times.Once
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.