0
0

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からテスト対象プロジェクトのApp.confgを取得できるようにする

Last updated at Posted at 2023-07-16

1. はじめに

  • MSTestクラスを使用して単体テストしようとした時にテスト対象プロジェクトのApp.configが参照できない問題を解決したい

2. 開発環境

  • C#
  • .Net 6
  • MSTest
  • Visual Stuido 2022
  • Windows 11

3. 問題点

  • テスト対象クラスでApp.Configの値を使用している場合、テストプロジェクトから参照できず、設定値がないことになる

3.1. テスト対象クラス

Class1.cs
public class Class1
{
    public int Add(int x, int y)
    {
        var value = ConfigurationManager.AppSettings["value"];
        return x + y + Convert.ToInt32(value);
    }
}

3.2. App.config

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<add key="Value" value="10" />
	</appSettings>
</configuration>

3.3. テストクラス

Class1Tests.cs
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var class = new Class1();
            Assert.AreEqual(class.add(1, 2), 10);
            // 毎回NGになる
            // expected: 13
            // actual: 3 → App.configからvalueが取得できないため
        }
    }

4. 回避策

  1. テストプロジェクト直下にApp.configをコピーして、名前をtesthost.dll.configに変更する
    image.png

  2. プロパティで出力ディレクトリにコピーを新しい場合はコピーするに設定する
    image.png

5. 参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?