Vector search is becoming an important part of modern .NET applications. It allows applications to find information based on meaning rather than relying only on exact keyword matches. For example, a user can search for "how to protect an application from unauthorized access" and receive documents discussing authentication, authorization, and access control, even if those exact words aren't in the query.
Implementing vector search is only one part of the work. Developers also need to verify that the search returns relevant results, that similarity ranking works correctly, and that database filters are applied as expected.
Testing vector search with mocked repositories or in-memory collections is not enough. Vector distance calculations, PostgreSQL operators, database indexes, and query translation all depend on the actual database provider and its configuration.
In this article, we will explore how to test vector search queries in an EF Core application using real PostgreSQL data and the pgvector extension. We will create test records, execute semantic search queries, verify similarity ordering, test relational filters, and identify common testing mistakes.
Why Test Vector Search With a Real Database?
Traditional EF Core queries can often be tested using an in-memory collection or mocked repository. However, vector search introduces database-specific functionality.
Consider the following query:
var results = await dbContext.Documents
.OrderBy(d =>
d.Embedding!.CosineDistance(queryEmbedding))
.Take(5)
.ToListAsync();This query uses CosineDistance() to calculate vector distance.
When EF Core executes this query against PostgreSQL with pgvector integration, the provider translates the operation into a PostgreSQL vector distance expression.
A mocked repository does not execute that SQL. An in-memory collection does not reproduce PostgreSQL's vector operators or index behavior.
As a result, a test might pass without proving that the actual database query works.
Real database testing helps verify:
EF Core correctly translates vector operations.
PostgreSQL accepts the generated vector query.
Stored embeddings have the expected dimensions.
Similarity ordering works correctly.
Relational filters are applied before results are returned.
Queries handle missing embeddings.
Database migrations and vector column mappings are correct.
For this reason, use real PostgreSQL integration tests for database-dependent vector search behavior.
Understanding the Test Scenario
Let's assume we are developing a document search application.
Each document contains a title, category, status, organization identifier, and embedding.
The application accepts a query embedding and returns the most relevant documents.
We will test the following scenarios:
Test scenario | Expected behavior |
|---|---|
Similarity search | Returns documents closest to the query vector |
Distance ordering | Places smaller cosine distances first |
Organization filtering | Returns documents belonging to the selected organization |
Status filtering | Excludes unpublished documents |
Missing embeddings | Excludes records without embeddings |
Empty results | Returns an empty collection when no records match |
Result limit | Returns no more than the requested number of records |
These tests cover both vector-specific behavior and normal relational query behavior.
Preparing the Application
Before writing tests, we need an EF Core entity and database context.
For this example, we will use PostgreSQL with pgvector.
Install the required packages in the application project:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Pgvector.EntityFrameworkCoreInstall the testing packages in the test project:
dotnet add package Microsoft.NET.Test.Sdk
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package Testcontainers.PostgreSqlTestcontainers allows tests to start a PostgreSQL container automatically. This makes it possible to run integration tests against an isolated database without depending on a manually maintained development database.
The PostgreSQL image used for testing must have pgvector installed. A pgvector-enabled image can be used instead of a standard PostgreSQL image.
Creating the Document Entity
Create a document entity with a vector property.
using Pgvector;
public class Document
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Category { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
public int OrganizationId { get; set; }
public Vector? Embedding { get; set; }
}The embedding is nullable because some documents may not have been processed by the embedding service.
For testing, we will use small three-dimensional vectors. This keeps test data easy to understand while allowing us to verify distance calculations.
The production embedding dimension must match the embedding model used by the application. The test database can use a separate schema or test-specific entity configuration if its vector dimension differs from production.
Configuring the DbContext
Create the EF Core database context.
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Document> Documents => Set<Document>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasPostgresExtension("vector");
modelBuilder.Entity<Document>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Title)
.HasMaxLength(250);
entity.Property(x => x.Category)
.HasMaxLength(100);
entity.Property(x => x.Status)
.HasMaxLength(50);
entity.Property(x => x.Embedding)
.HasColumnType("vector(3)");
});
}
}Notice that the vector column is configured with three dimensions.
entity.Property(x => x.Embedding)
.HasColumnType("vector(3)");This is intentional for the test example. Every non-null vector inserted into this column must contain exactly three values.
The model configuration also declares the PostgreSQL vector extension. The extension must be available in the database before the application executes vector queries.
Creating a Vector Search Service
It is useful to keep search logic in a dedicated service. This makes the application easier to maintain and allows integration tests to exercise the same query logic used by the application.
using Microsoft.EntityFrameworkCore;
using Pgvector;
public class DocumentSearchService
{
private readonly AppDbContext _dbContext;
public DocumentSearchService(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<Document>> SearchAsync(
Vector queryEmbedding,
int organizationId,
int limit = 5)
{
return await _dbContext.Documents
.AsNoTracking()
.Where(d =>
d.OrganizationId == organizationId &&
d.Status == "Published" &&
d.Embedding != null)
.OrderBy(d =>
d.Embedding!.CosineDistance(queryEmbedding))
.Take(limit)
.ToListAsync();
}
}The service applies three important conditions.
First, it restricts results to the requested organization. Second, it returns only published documents. Third, it excludes records without embeddings.
After filtering, it orders the remaining records using cosine distance and applies the requested result limit.
This is the query that our integration tests will execute against PostgreSQL.
Setting Up PostgreSQL With Testcontainers
Instead of connecting tests to a shared database, we can start a temporary PostgreSQL container for the test run.
Create a test fixture:
using Testcontainers.PostgreSql;
using Xunit;
public class PostgreSqlFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer _container =
new PostgreSqlBuilder()
.WithImage("pgvector/pgvector:pg16")
.WithDatabase("vectortest")
.WithUsername("testuser")
.WithPassword("testpassword")
.Build();
public string ConnectionString =>
_container.GetConnectionString();
public async Task InitializeAsync()
{
await _container.StartAsync();
}
public async Task DisposeAsync()
{
await _container.DisposeAsync();
}
}The container uses a PostgreSQL image that includes pgvector.
The connection string is available after the container starts. Tests can use it to create an EF Core context.
Container image tags should be selected deliberately and pinned to a version suitable for the project. Avoid using an unverified image tag in a production CI pipeline.
Creating a Test Database Context
Next, create a helper method that configures EF Core using the container connection string.
using Microsoft.EntityFrameworkCore;
public static class TestDbContextFactory
{
public static AppDbContext Create(string connectionString)
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(
connectionString,
npgsql => npgsql.UseVector())
.Options;
return new AppDbContext(options);
}
}This configuration is important because the tests must use the same PostgreSQL provider and vector integration as the application.
Using a different provider could cause the tests to behave differently from production.
Creating Test Data
Now we need documents with predictable embeddings.
We will use the following vectors:
Document | Embedding | Organization |
|---|---|---|
Authentication Guide | [1, 0, 0] | 10 |
Identity Security | [0.9, 0.1, 0] | 10 |
Database Backup | [0, 1, 0] | 10 |
API Security | [0.8, 0.2, 0] | 20 |
Network Monitoring | [0, 0, 1] | 10 |
For the first test, the query vector will be [1, 0, 0].
Authentication Guide has the same vector as the query, so its cosine distance should be zero. Identity Security has a similar vector and should appear near the top.
Create a test data helper:
using Pgvector;
public static class DocumentTestData
{
public static List<Document> CreateDocuments()
{
return new List<Document>
{
new Document
{
Title = "Authentication Guide",
Category = "Security",
Status = "Published",
OrganizationId = 10,
Embedding = new Vector(
new float[] { 1f, 0f, 0f })
},
new Document
{
Title = "Identity Security",
Category = "Security",
Status = "Published",
OrganizationId = 10,
Embedding = new Vector(
new float[] { 0.9f, 0.1f, 0f })
},
new Document
{
Title = "Database Backup",
Category = "Database",
Status = "Published",
OrganizationId = 10,
Embedding = new Vector(
new float[] { 0f, 1f, 0f })
},
new Document
{
Title = "API Security",
Category = "Security",
Status = "Published",
OrganizationId = 20,
Embedding = new Vector(
new float[] { 0.8f, 0.2f, 0f })
},
new Document
{
Title = "Network Monitoring",
Category = "Infrastructure",
Status = "Published",
OrganizationId = 10,
Embedding = new Vector(
new float[] { 0f, 0f, 1f })
}
};
}
}
Join the conversation! Your thoughts help the community grow.