1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#のMSTestでPrivateメソッド、Privateフィールドをテストする

Last updated at Posted at 2023-07-08

1. はじめに

  • C# .NET6でPrivateObject, PrivateTypeが使用できないため代替する方法を考える
  • MicrosoftのGitHubを参考に、あまり独自のテストクラスにならないようにしたい

2. 開発環境

  • C#
  • Visual Stduio 2022
  • MSTest
  • Windows 11

3. PrivateObject、PrivateTypeクラスの代替

  • MicrosoftのGitHubよりPrivateObjectPrivateType.csを使用する

4. Privateメソッドのテスト

4.1 テスト対象クラス

public Class1() { }

private int Sum(int x,int y)
{
    return x + y;
}

4.2. テストクラス

Class1Tests.cs
[TestClass()]
public class Class1Tests
{
    [TestMethod()]
    public void Test_Sum()
    {
        var class1 = new Class1();
        var pbObj = new PrivateObject(class1);
        var actual = (int)pbObj.Invoke("Sum", 1, 2);
        Assert.AreEqual(3, actual);
    }
}

4.3. テスト結果

image.png

5. Private staticメソッドのテスト

5.1 テスト対象クラス

public Class1() { }

private static int Sum(int x,int y)
{
    return x + y;
}

5.2. テストクラス

Class1Tests.cs
[TestMethod()]
public void Test_Sum()
{
    PrivateType privateType = new PrivateType(typeof(Class1));
    int actual = (int)privateType.InvokeStatic("Sum", 1, 2);
    Assert.AreEqual(3, actual);
}

5.3. テスト結果

image.png

6. 基底クラスのPrivateメソッドのテスト

6.1 テスト対象クラス

BseClass.cs
public class BaseClass
{
    private int Sum(int x,int y)
    {
        return x + y;
    }
}
SubClass.cs
public class SubClass: BaseClass
{
    public SubClass()
    {
        
    }
}

6.2. テストクラス

Class1Tests.cs
[TestClass()]
public class Class1Tests
{
    [TestMethod()]
    public void Test_Sum()
    {
        var subClass = new SubClass();
        var pbObj = new PrivateObject(subClass, new PrivateType(typeof(BaseClass)));
        var actual = (int)pbObj.Invoke("Sum", 1 ,2);
        Assert.AreEqual(3, actual);
    }
}

6.3. テスト結果

image.png

7. Privateフィールドのテスト

7.1. テスト対象クラス

MyClass.cs
public class MyClass
{
    private string name;
    public MyClass(string name)
    {
        this.name = name;
    }
}

7.2. テストクラス

Class1Tests.cs
[TestMethod()]
public void Test_Name()
{
    var myClass = new MyClass("Hello World");
    var pbObj = new PrivateObject(myClass);
    var name = (string)pbObj.GetField("name");
    Assert.AreEqual("Hello World", name);
}

7.3. テスト結果

image.png

8. 参考文献

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?