Reputation: 88
I'm new to CosmosDB and azure functions and have no idea how it works.
Anyway a project I'm working on is using CosmosDB. They have created some azure functions to insert and get data in/out from Cosmos DB. I have to tests these function by mocking the Cosmos DB in my local machine.
How can I test these methods? How to mock Cosmos DB in my local machine?
Upvotes: 1
Views: 3135
Reputation: 23792
Since you have already installed Cosmos DB Emulator, you could operate documents in Cosmos DB locally with SDK or on the data explorer directly.
Sample Insert Document Code:
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Threading.Tasks;
namespace JayGongDocumentDB.module
{
class TestEmulator
{
private static readonly string endpointUrl = "https://localhost:8081";
private static readonly string authorizationKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
private static readonly string databaseId = "db";
private static readonly string collectionId = "coll";
private static DocumentClient client;
public static async Task TestAsync()
{
client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
var uri = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
var doc = new Document();
doc.SetPropertyValue("name", "jay");
await client.CreateDocumentAsync (
"/dbs/db/colls/coll", doc,null);
Console.WriteLine("insert success");
}
}
}
You could find the endpointUrl and key in azure cosmos db emulator:
About azure function, you could follow the official doc to create Cosmos DB Trigger Azure Function.
using System.Collections.Generic;
using Microsoft.Azure.Documents;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace TestAzureFunction
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([CosmosDBTrigger(
databaseName: "db",
collectionName: "coll",
ConnectionStringSetting = "CosmosdbString",
LeaseCollectionName = "leases")]IReadOnlyList<Document> input, TraceWriter log)
{
if (input != null && input.Count > 0)
{
log.Verbose("Documents modified " + input.Count);
log.Verbose("First document Id " + input[0].Id);
}
}
}
}
Hope it helps you.
Upvotes: 2