[英]How can I use dependency injection in a unit test?
我正在嘗試對通過依賴注入訪問的 function 進行單元測試,但當它通過測試資源管理器時,我不知道如何使其運行。
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RDM_API.Models;
namespace RDM_API.UnitTest
{
[TestClass]
public class AddSession_Test
{
private IRDM_Functions test;
public AddSession_Test(IRDM_Functions Test)
{
this.test = Test;
}
[TestMethod]
public void addSession_Test_True()
{
//Arange
string sessionId = "apples";
string user = "Brendan";
string sessionName = "Test";
bool expected = true;
//Act
bool actual = test.AddSessionAndUserId(sessionId, user, sessionName);
//Assert
Assert.AreEqual(expected, actual);
}
在這種情況下,將其稱為test
並且 Visual Studio 錯誤檢查器沒有顯示任何問題,我認為正在發生的事情是因為注入沒有用[Test]
標記。 對此的任何更正將不勝感激。 我已嘗試將 go 重新使用new
但這會導致錯誤Error CS7036 There is no argument given that corresponds to the required formal parameter 'configuration' of 'RDM_Functions.RDM_Functions(IConfiguration)
和任何test.
函數錯誤為Error CS0103 The name 'test' does not exist in the current contex
。有人告訴我應該模擬Iconfiguration
,但我不確定如何這樣做,對此有任何幫助都會很棒。
我不確定它是如何/為什么工作的,但是通過使用以下代碼
namespace RDM_API.UnitTest
{
[TestClass]
public class sessionExists_Test
{
private readonly IRDM_Functions rdm;
[TestMethod]
public void sessionExists_Test_True()
{
//Arange
Models.RDM_Functions test = new Models.RDM_Functions((Microsoft.Extensions.Configuration.IConfiguration)rdm);
string sessionId = "banana";
string user = "glenn";
string sessionName = "kong";
bool expected = true;
test.deleteSession(sessionId, user);
test.AddSessionAndUserId(sessionId, user, sessionName);
//Act
bool actual = test.sessionExists(sessionId);
//Assert
Assert.AreEqual(expected, actual);
test.deleteSession(sessionId, user);
}
}
}
配置放入class中通常的position private readonly IRDM_Functions rdm;
然后使用new
來引用它Models.RDM_Functions test = new Models.RDM_Functions((Microsoft.Extensions.Configuration.IConfiguration)e);
,測試資源管理器能夠使用這些功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.