单元测试和对象的范围 - 如何测试私有/内部方法等?单元测试、对象、范围、测试

2023-09-04 10:39:34 作者:她始终一个人

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

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.

 
精彩推荐
图片推荐