How to read data from Cosmos Db emulator in Unit test case

877 views Asked by At

I am writing unit test cases and would like to read data from Cosmos Db emulator. I have achieved this far and would need help in reading data now from Emulator. How can I read data from container where lets say I have data with Id = "Test"

public class DataFixtures
{
    public DataFixtures()
    {
        app.CreateDefaultLoggerFactory();
    }
}


[CollectionDefinition("Tabulardata collection")]
public class DataCollection : ICollectionFixture<DataFixture>
{
}



[Collection( "Tabulardata collection" )]
public class DataTests
{
    private static readonly string CosmosEndpoint = "https://localhost:8081";
    private static readonly string EmulatorKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
    private static readonly string DatabaseId = "Recordings";
    private static readonly string RecordingCollection = "testdata";
    string Root = Directory.GetParent( Directory.GetCurrentDirectory() ).Parent.Parent.FullName;


    private void ReadConfig()
    {
        var client = new DocumentClient( new Uri( CosmosEndpoint ), EmulatorKey,
            new ConnectionPolicy
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp

            } );
        var databaseCreationResult = client.CreateDatabaseAsync( new Database { Id = DatabaseId } ).Result;
        var collectionCreationResult = client.CreateDocumentCollectionAsync( UriFactory.CreateDatabaseUri( DatabaseId ),
            new DocumentCollection { Id = RecordingCollection } ).Result;            
    
    }
1

There are 1 answers

2
Tiny Wang On BEST ANSWER

Try this?

private void ReadConfig()
    {
        var client = new DocumentClient( new Uri( CosmosEndpoint ), EmulatorKey,
            new ConnectionPolicy
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp

            } );
        var databaseCreationResult = client.CreateDatabaseAsync( new Database { Id = DatabaseId } ).Result;
        var collectionCreationResult = client.CreateDocumentCollectionAsync( UriFactory.CreateDatabaseUri( DatabaseId ),
            new DocumentCollection { Id = RecordingCollection } ).Result;

var docUri = UriFactory.CreateDocumentUri(DatabaseId, RecordingCollection, "Test");
    var response = await client.ReadDocumentAsync(docUri,
            new RequestOptions { PartitionKey = new PartitionKey("partitionkey_value") });
        Console.WriteLine("Document read by Id {0}", response.Resource);          
    
    }

Refer to this tutorial and this sample code.

This is my testing result:

enter image description here