单元测试和对象的范围 - 如何测试私有/内部方法等? [英] Unit testing and the scope of objects - how to test private/internal methods etc?

查看:132
本文介绍了单元测试和对象的范围 - 如何测试私有/内部方法等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个项目,是一个类库。我有一个类在库和这个类有一些方法,这些方法只使用类中。像这样的:

Let's say I have a project that is a class library. I have a class in that library and this class has some methods that are used inside the class only. Like this:

public class MyClass
{
  public void MyPublicMethod
  {
    int k

    // do something ...

    int z = MyInternalMethod(k);
    // do something else ...

  }

  internal int MyInternalMethod(int i)
  {
        // do something ...

  }
}

现在我想编写单元测试这些方法。我想创建一个单元测试项目,从它引用NUnit的,写这样的事情

Now I want to write unit tests for these methods. I would create a "Unit Tests" project, reference the nunit from it and write something like this

[TestFixture]
public class UnitTests
{
  private MyClass myClass;

  [SetUp]
  public void SetupTest
  {
    myClass = new MyClass();
  }

  [Test]
  public void TestMyInternalMethod
  {
    int z = 100;
    int k = myClass.MyInternalMethod(z); //CAN NOT DO THIS!
    Assert.AreEqual(k, 100000);
  }

  [TearDown]
  public void TearDown
  {
    myClass = null;
  }
}

当然,我不能这样做,因为MyInternalMethod范围本。什么是正确的方式来处理这种情况?

Of course, I can not do this, because of the MyInternalMethod scope. What would be the proper way to handle this situation?

推荐答案

您可以看到内部的某些组件使用的 InternalsVisibleToAttribute

You can make internals visible to certain assemblies by using the InternalsVisibleToAttribute.

这篇关于单元测试和对象的范围 - 如何测试私有/内部方法等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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