使用 Ninject 在不使用构造函数注入的情况下注入依赖项 - 单元测试

Inject Dependency without using Constructor injection using Ninject - Unit Tests

我正在为现有的 .NET Framework 4.5 API 项目创建单元测试。现有项目在设计上具有无参数构造函数,依赖注入是根据下面的 class 使用 Ninject.

实现的

我想模拟接口并创建一个 class 实例用于测试,如下所示,但构造函数是无参数的。我不知道如何注入我的 Mock member.Object。主要目标是我不想更改现有 classes 的设计,除非没有其他办法。

public class MemberController : ApiController
{
    StandardKernel DependencyKernel;
    private IMember member;
    
    public MemberController()
    {
        DependencyKernel = new StandardKernel();
        DependencyKernel.Load(Assembly.GetExecutingAssembly());
        member = DependencyKernel.Get<IMember>();
    }

    [HttpPost]
    public HttpResponseMessage AddMember(MemberRequest model)
    {
        try
        {
            int memberRecords;
            
            member.SaveMember(model, out memberRecords);

            if (memberRecords > 0)
                return new HttpResponseMessage { StatusCode = HttpStatusCode.Conflict, Content = new StringContent("Member with same reference exists") };
            else
                return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("Member added successfully") };
        }
        catch (Exception ex)
        {
            return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message) };
        }
    }
}

//测试Class

public class MemberControllerTests
{
    StandardKernel DependencyKernel;
    private MemberController memberController;
    Mock<IMember> member = new Mock<IMember>();

    public MemberControllerTests()
    {
        DependencyKernel = new StandardKernel();
        DependencyKernel.Load(Assembly.GetExecutingAssembly());
    }

    [SetUp]
    public void Setup()
    {
        
    }

    [Test]
    public void should_AddMember()
    {
        //Arrange
        MemberRequest member = new MemberRequest{ };
        int memberRecords;

        member.Setup(x => x.SaveMember(member, out memberRecords));

        memberController = new MemberController(member.Object); //This will obviously not work, the MemberController has parameterless constructor
        //Act
        var result = MemberController.AddMember(member);
        //Assert
        Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);
    }
}

This post 有问题的答案。如果 IMember 成员 属性 在 MemberController 中创建 public,我可以新建 MemberController class 并将其成员 属性 的值设置为 MOCK。