[Unit Test]How to access internal class of other project in the UnitTest Project

紀錄一下再寫單元測試時,如何測試internal class

前幾天撰寫單元測試,要測試幾隻internal class是否如預期,

查了一下MSDN發現原來可以透過InternalsVisibleToAttribute Class輕鬆存取,簡單紀錄一下

我有一個TestRedis project,裡面有一隻 MyLogger 的internal class,

namespace TestRedis
{
    internal class MyLogger
    {
        public MyLogger()
        {
            Console.WriteLine("MyLogger Init");
        }
       

        public void WriteLog(string inmsg)
        {
            Console.WriteLine(inmsg);
        }
    }
}

如要讓我的Redis.Tests project可以順利存取這支internal class,

我們必須在AssemblyInfo.cs of TestRedis project 填入下面code

[assembly: InternalsVisibleTo("Redis.Tests")]

note:Redis.Tests is assembly name of Redis.Tests projec

 

現在你可以正常測試這隻internal class

public class ConsoleOutput : IDisposable
    {
        private readonly StringWriter _stringWriter;
        private readonly TextWriter _originalOutputTextWriter;

        public ConsoleOutput()
        {
            _stringWriter = new StringWriter();
            _originalOutputTextWriter = Console.Out;
            Console.SetOut(_stringWriter);
        }

        public string GetOuput()
        {
            return _stringWriter.ToString();
        }

        public void Dispose()
        {
            Console.SetOut(_originalOutputTextWriter);
            _stringWriter.Dispose();
        }
    }


note: you have to add reference of TestRedis

 

參考

InternalsVisibleToAttribute Class