如何在单元测试中检查方法是否被调用 [英] how to check if method is being called or not in unit testing

查看:930
本文介绍了如何在单元测试中检查方法是否被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述







我试图找出一种方法来测试我的测试中是否调用了某个方法我可能会使用一些专业知识,因为我是假货新手。首先让我试着解释一下我的问题



ok所以我有一个类似下面的方法



Hi


I am trying to figure out a way to test if a method is called or not in one of my test case and I might use some expertise as i am new to fakes. First let me try to explain my problem

ok so i have a method like below one

public static void Mthod1 (parm1, parm2, parm3)
{

// call to another method method2

method2(parm1);

if(parm2 != null)
{
return;
}

method3(parm3);

}





现在我正在使用假货编写单元测试,其中我是shiming method2和method3.if parm2是null方法返回,并且不调用method3。我的问题是如何在我的单元测试中证明方法3没有被调用。



提前谢谢。



now i am writing unit test using fakes where i am shiming method2 and method3.if parm2 is null method return and method3 is not called. my problem is how to prove in my unit test that method3 is not called.

Thanks in advance.

推荐答案

如果您需要知道调用外部接口方法的次数,请使用一些模拟框架。另请参见使用什么C#模拟框架? [ ^ ]。

这些框架提供了断言您希望调用方法的次数和参数的方法。



如果方法是一个内部方法测试单元(UUT),然后你需要添加一些内部测试代码。



在任何情况下,你的主要挑战将是依赖的decopling。请参阅控制反转 [ ^ ],更具体地说,例如依赖注入 [ ^ ]以便您可以将模拟的外部代码插入UUT,并可能将一些内部测试代码插入UUT。



干杯

Andi
If you need to know how many times an external interface method is called, use some mocking framework. See also What C# mocking framework to use?[^].
These frameworks provide means to assert how many times and with what parameters you expect the method to be called.

If the method is an interal method of the Unit-Under-Test (UUT), then you need to add some internal test code.

In any case, your main challenge will be the decopling of the dependencies. See Inversion of Control[^] and more specifically e.g. Dependency Injection[^] so that you can plug the mocked external code to the UUT and maybe plug in some internal test code to the UUT.

Cheers
Andi


这篇关于如何在单元测试中检查方法是否被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆