CosmosDB Trigger, Input, and Output binding support for the Azure Functions Test Framework.
dotnet add package AzureFunctions.TestFramework.CosmosDB| Binding | Attribute | Description |
|---|---|---|
[CosmosDBTrigger] |
Trigger | Receives a batch of changed documents from the CosmosDB change feed |
[CosmosDBInput] |
Input | Reads documents from CosmosDB (point-read or query) |
[CosmosDBOutput] |
Output | Writes documents to CosmosDB — captured via FunctionInvocationResult |
Use InvokeCosmosDBAsync to simulate a CosmosDB change-feed trigger with a batch of changed documents.
var documents = new[]
{
new TodoItem { Id = "1", Title = "Buy milk", IsComplete = false },
new TodoItem { Id = "2", Title = "Write tests", IsComplete = true }
};
var result = await host.InvokeCosmosDBAsync("ProcessCosmosDocuments", documents);
Assert.True(result.Success);var json = """[{"id":"1","title":"Buy milk"},{"id":"2","title":"Write tests"}]""";
var result = await host.InvokeCosmosDBAsync("ProcessCosmosDocuments", json);
Assert.True(result.Success);Register fake documents via the builder so they are injected automatically for every invocation:
var host = await new FunctionsTestHostBuilder()
.WithFunctionsAssembly(typeof(MyFunction).Assembly)
.WithHostBuilderFactory(Program.CreateHostBuilder)
// Single document for [CosmosDBInput(databaseName: "MyDb", containerName: "Items")]
.WithCosmosDBInputDocuments("MyDb", "Items",
new TodoItem { Id = "1", Title = "Injected item", IsComplete = false })
.BuildAndStartAsync();Use WithCosmosDBInputDocuments<T>(databaseName, containerName, IReadOnlyList<T> documents) to inject a list
of documents, and WithCosmosDBInputJson(databaseName, containerName, json) to inject raw JSON.
[Function("ReadCosmosItem")]
public void Run(
[QueueTrigger("items-queue")] string queueMessage,
[CosmosDBInput(databaseName: "MyDb", containerName: "Items", Id = "%itemId%")] TodoItem? item)
{
if (item is not null)
_logger.LogInformation("Read item: {Title}", item.Title);
}Output bindings are captured automatically via FunctionInvocationResult:
var result = await host.InvokeCosmosDBAsync("CreateCosmosDocument", documents);
Assert.True(result.Success);
var written = result.ReadOutputAs<TodoItem>("outputDocument");
Assert.Equal("expected-id", written?.Id);[Function("CreateCosmosDocument")]
[CosmosDBOutput(databaseName: "MyDb", containerName: "Items")]
public TodoItem? Run([CosmosDBTrigger(...)] IReadOnlyList<TodoItem> documents)
{
return documents.FirstOrDefault();
}Add the CosmosDB package reference to your test project and all four function-app test flavours:
<PackageReference Include="AzureFunctions.TestFramework.CosmosDB" />See the 4-flavour matrix test pattern for the concrete test class structure.