DEV Community

Masui Masanori
Masui Masanori

Posted on

3 2

[ASP.NET Core][Entity Framework Core] Logging for xUnit projects

Intro

To debug testing codes, I want to add loggers into my xUnit project.

Environments

  • .NET ver.6.0.101
  • Microsoft.NET.Test.Sdk ver.16.11.0
  • xUnit ver.2.4.1
  • xunit.runner.visualstudio ver.2.4.3
  • coverlet.collector ver.3.1.0
  • Microsoft.EntityFrameworkCore.Sqlite ver.6.0.1
  • Moq ver.4.16.1

Add loggers

In xUnit projects, I can't use "Console.WriteLine()" to log.
According to the document, to run tests in parallel, I should use "ITestOutputHelper".

BookTest.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
using BookshelfSample.Books;
using BookshelfSampleTest.Models;
using BookshelfSample.Models;
using BookshelfSample.Models.SeedData;
using Xunit.Abstractions;

namespace BookshelfSampleTest.Books;
public class BooksTest: IDisposable
{
...
    private readonly ITestOutputHelper output;
    public BooksTest(ITestOutputHelper output)
    {
        this.output = output;
        this.output.WriteLine("Hello");
...
    }
    public void Dispose()
    {
        this.databaseFixture.Dispose();
    }
...
Enter fullscreen mode Exit fullscreen mode

To output logs, I have to add "logger" option into "dotnet test" command.

dotnet test BookshelfSampleTest --logger "console;verbosity=detailed"
Enter fullscreen mode Exit fullscreen mode

Result

Image description

How I shall run tests?

As same as this post, I run tests by ".NET Core Test Explorer" on VSCode.

But the logs aren't written in "OUTPUT" tab.

Test run for /home/example/Documents/workspace/BookshelfSample/BookshelfSampleTest/bin/Debug/net6.0/BookshelfSampleTest.dll (.NETCoreApp,Version=v6.0)
Microsoft (R) Test Execution Command Line Tool Version 17.0.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
Results File: /tmp/test-explorer-kxye5v/0.trx

Passed!  - Failed:     0, Passed:     1, Skipped:     0, Total:     1, Duration: < 1 ms - /home/example/Documents/workspace/BookshelfSample/BookshelfSampleTest/bin/Debug/net6.0/BookshelfSampleTest.dll (net6.0)
Enter fullscreen mode Exit fullscreen mode

Because I use NLog in the ASP.NET Core project, I tried to use NLog in the xUnit project.
But I couldn't resolve the problem.

And I also tried "xunit.NLog".
However, it didn't seem to be compatible with .NET 6.

So when I want to log some data to write test codes, I run tests by command.
After finishing creating them, I run them by ".NET Core Test Explorer".

For Entity Framework Core projects

To log Entity Framework Core projects, I can add "ITestOutputHelper" into DbContext options.

SharedDatabaseFixture.cs

using BookshelfSample.Models;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Xunit.Abstractions;

namespace BookshelfSampleTest.Models;
public class SharedDatabaseFixture: IDisposable
{
    private readonly ITestOutputHelper output;
    private readonly SqliteConnection connection;
    public SharedDatabaseFixture(ITestOutputHelper output)
    {
        this.output = output;
        this.connection = new SqliteConnection("DataSource=:memory:");
        this.connection.Open();
    }
    public void Dispose() => this.connection.Dispose();
    public BookshelfContext CreateContext()
    {
        var result = new BookshelfContext(new DbContextOptionsBuilder<BookshelfContext>()
            .UseSqlite(this.connection)
            .EnableSensitiveDataLogging()
            .LogTo(this.output.WriteLine)
            .Options);
        result.Database.EnsureDeleted();    
        result.Database.EnsureCreated();
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay