使用 NUnit在.NET Core Web API專案上進行單元測試

在.NET Core Web API專案裡,用相依性注入,如何將IConfiguration填入NUnit單元測試專案裡?

由於工作上的需要,加入NUnit單元測試專案,但由於該Web API(.NET 7)專案採用相依性注入,如下程式碼:

HistoryManager.cs

public class HistoryManager : IHistoryManager
{
	internal readonly string _logTransPath;

	public HistoryManager(IConfiguration configuration)
	{
		_logTransPath = configuration.GetSection("WindowsServiceLog")["LogTransPath"];
	}
	
	//略...
}

當要在NUnit單元測試專案裡引用IConfiguration就卡住,因此解法是改用ConfigurationBuilder模擬從appsettings.json擷取的資料,如下:

UnitTest_ServiceImpletment.cs



using Microsoft.Extensions.Configuration;

namespace HermesAdapterWebAPITests
{
	[TestFixture]
	public class Tests
	{
		private HistoryManager _historyManager;

		[SetUp]
		public void Setup()
		{
			var myConfig = new Dictionary<string, string>
			{
				{ "WindowsServiceLog:LogTransPath", "D:\\TestWinsowsService\\Log_Trans" }
			};

			var config = new ConfigurationBuilder()
				.AddInMemoryCollection(myConfig)
				.Build();

			_historyManager = new HistoryManager(config);
		}

		/// <summary>
		/// 測試產生檔案路徑之正確性
		/// </summary>
		[Test]
		public void TestGenerateFilePath()
		{
			HistorySearchModel searchModel = new HistorySearchModel()
			{
				Date = new DateTime(2024, 09, 25)
			};

			string getFilePathResult = _historyManager.GenerateFilePath(searchModel, "HermesMessage");
			string expectedString = "D:\\TestWinsowsService\\Log_Trans\\202409\\20240925_HermesMessage.txt";
			Assert.AreEqual(expectedString, getFilePathResult);
		}
	}
}

如有更好的解法,歡迎大家提出來討論。