【发布时间】:2021-05-21 00:59:43
【问题描述】:
我正在尝试对通过依赖注入访问的函数进行单元测试,但当它通过测试资源管理器时,我不知道如何使其运行。
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] 标记。对此的任何更正将不胜感激。我试图回到使用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 但我不确定该怎么做所以这方面的任何帮助都会很棒。
【问题讨论】:
-
为什么有些代码只能通过依赖注入来访问?无法在其他地方访问它并没有多大意义,因为如果您无法在其他地方访问它,您的依赖注入容器也将无法访问它。
-
由于我已将依赖注入添加到代码中,因此我无法使用
new语句而不会出现错误Error CS7036 There is no argument given that corresponds to the required formal parameter 'configuration' of 'Class.Class(Iconfiguration) -
嗯,当然。您需要将
IConfiguration传递给新的。你应该模拟IConfiguration。 -
我目前不确定如何做到这一点,我已经编辑了问题,但与此同时我会尝试找出如何做到这一点。
标签: c# unit-testing dependency-injection new-operator