DbCommandInterceptor is an Entity Framework Core base class for observing database command execution. A test interceptor can override ReaderExecutingAsync, inspect command.CommandText, write the generated SQL, and delegate to the base implementation. section 9.4.1
A practical test interceptor typically:
- Accepts ITestOutputHelper so parallel xUnit tests keep their output associated with the correct test. section 9.4.1
- Overrides ReaderExecutingAsync and receives the DbCommand, event data, interception result, and cancellation token. section 9.4.1
- Returns ValueTask because the interceptor commonly performs synchronous SQL inspection or manipulation. section 9.4.1
- Registers through DbContextOptionsBuilder.AddInterceptors when constructing the test DbContext. section 9.4.1
Listing 9.6 LogSqlInterceptor logging SQL generated by EF Core
using System.Data.Common; #1
using Microsoft.EntityFrameworkCore.Diagnostics; #2
using Xunit.Abstractions; #3
namespace ManningBooksApi.Tests;
public class LogSqlInterceptor : DbCommandInterceptor
{
private readonly ITestOutputHelper _testOutput; #4
public LogSqlInterceptor(ITestOutputHelper testOutput)
=> _testOutput = testOutput;
public override
ValueTask<InterceptionResult<DbDataReader>> #5
ReaderExecutingAsync( #6
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result,
CancellationToken cancelToken)
{
_testOutput.WriteLine(command.CommandText.Trim()); #7
return base.ReaderExecutingAsync( #8
command, eventData, result, cancelToken);
}
}
Inspect the focused C# implementation that logs generated SQL through ITestOutputHelper. section 9.4.1
Generated SQL inspection
A controller test registers LogSqlInterceptor with its DbContext options. A query for a book produces SQL containing a parameter such as @__id_0, making the executed command visible in the test output. section 9.4.1
