Ninject DI参数传递给单元测试

时间:2018-04-19 20:35:37

标签: c# .net ninject

它是具有ILogger依赖性的构造函数

 public Book(string isbn, string author, string title, string publisher, int publishYear, ushort pageNumber, decimal price, ILogger logger)
    {
        Isbn = isbn;
        Author = author;
        Title = title;
        Publisher = publisher;
        PublishYear = publishYear;
        PageNumber = pageNumber;
        Price = price;
        _logger = logger;

        _logger.Log(LogLevel.Info, "Book constructor has been invoked");
    }

我的单元测试尝试通过Ninject框架解决它

    [TestCase("9783161484100", "Some Name", "C# in a nutshell", "Orelly", 2014, (ushort)900, 60, ExpectedResult = "Some Name Orelly")]
    [Test]
    public string FormatBook_FortmattingBooksObject_IsCorrectString(string isbn, string author, string title, string publisher, int year, ushort pages, decimal price)
    {
        using (IKernel kernel = new StandardKernel())
        {
            var book = kernel.Get<Book>();    

            Console.WriteLine(book.FormatBook(book.Author, book.Publisher));

            return book.FormatBook(book.Author, book.Publisher);
        }

    }

问题是,如何注入依赖项并将我的参数传递给构造函数?

2 个答案:

答案 0 :(得分:2)

没有必要在单元测试中注入东西。只需使用模拟对象作为记录器:

[TestCase("9783161484100", "Some Name", "C# in a nutshell", "Orelly", 2014, (ushort)900, 60, ExpectedResult = "Some Name Orelly")]
[Test]
public string FormatBook_FortmattingBooksObject_IsCorrectString(string isbn, string author, string title, string publisher, int year, ushort pages, decimal price)
{
        ILogger fakeLogger = ...; //Create some mock logger for consumption
        var book = new Book(isbn, author, title, publisher, year, pages, price, fakeLogger); 
        Console.WriteLine(book.FormatBook(book.Author, book.Publisher));

        return book.FormatBook(book.Author, book.Publisher);        
}

这并不是说内核也不能由内核提供,如果您这样选择,但是您必须先设置它然后才能获得它:

[TestCase("9783161484100", "Some Name", "C# in a nutshell", "Orelly", 2014, (ushort)900, 60, ExpectedResult = "Some Name Orelly")]
[Test]
public string FormatBook_FortmattingBooksObject_IsCorrectString(string isbn, string author, string title, string publisher, int year, ushort pages, decimal price)
{
    INinjectModule module = ...;//Create a module and add the ILogger here
    using (IKernel kernel = new StandardKernel(module))
    {
        var fakeLogger = kernel.Get<ILogger>(); //Get the logger  
        var book = new Book(isbn, author, title, publisher, year, pages, price, fakeLogger); 
        Console.WriteLine(book.FormatBook(book.Author, book.Publisher));

        return book.FormatBook(book.Author, book.Publisher);
    }

}

答案 1 :(得分:0)

正如已经说过的,在单元测试中,您通常不需要使用容器。但关于更一般的问题:

  

如何将我的参数传递给构造函数?

这样你就可以这样做:

kernel.Get<Book>(
    new ConstructorArgument("isbn", "123"), 
    new ConstructorArgument("author", "XYZ")
    ...
    );