简体   繁体   English

如何使用 Moq C# 在公共方法中对私有方法进行单元测试?

[英]How to unit test a private method inside a public method using Moq C#?

I have a public class a and I want to test its public method b.我有一个公共 class a,我想测试它的公共方法 b。 Its a void method.它是一种无效的方法。 Q1 - What should I test in this void method? Q1 - 我应该在这个 void 方法中测试什么? Q2 - How can I avoid testing the private methods that are being called in public methods? Q2 - 如何避免测试在公共方法中调用的私有方法?

I am using Moq framework.我正在使用 Moq 框架。

public class a
{

  public void b( x, y ,z)
  {
    c(y, z)
    d(x)
  }

  private void c(i, j)
  {
  }

  private void d(k)
  {
  }

}

All the methods are in same class.所有方法都在同一个 class 中。

What should I test in this void method?我应该在这个 void 方法中测试什么?

A void method always has a side effect. void 方法总是有副作用。 If not, it would be useless.如果没有,那将毫无用处。 So you measure that side effect.所以你测量那个副作用。

How can I avoid testing the private methods that are being called in public methods?如何避免测试在公共方法中调用的私有方法?

You don't avoid testing c and d implicitly .您不会避免隐式测试cd They are required for b to do its job. b需要它们来完成它的工作。 Without c and d , b would be empty and thus not fulfill the test criteria.如果没有cdb将为空,因此不符合测试标准。 What you should avoid is testing private methods explicitly .您应该避免的是显式测试私有方法。

If you wanted to avoid testing c and d , you could inline them both into b - which makes size, complexity and readability of b worse.如果您想避免测试cd ,您可以将它们都内联到b中 - 这会使b的大小、复杂性和可读性更差。 You certainly don't want that.你当然不希望那样。

Why don't you want to test private methods explicitly ?为什么不想显式测试私有方法? Because you're testing an implementation detail and make the code rigid.因为您正在测试实现细节并使代码变得僵硬。 If you expect method c to exist in a test, a developer cannot remove it.如果您希望方法c存在于测试中,则开发人员无法将其删除。 But maybe it could be removed, eg because it's so simple that it can actually be inlined.但也许它可以被删除,例如因为它是如此简单以至于它实际上可以被内联。 Developers need some flexibility.开发人员需要一些灵活性。 Otherwise they change something and dozens of tests fail, which creates a lot of work.否则,他们会改变一些东西,导致数十个测试失败,这会产生大量工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM