Re: [mongodb-user] How do I mock Mongo database with moq

2,855 views
Skip to first unread message

Russell Bateman

unread,
Nov 7, 2012, 12:36:45 PM11/7/12
to mongod...@googlegroups.com
Richard,

I'm a Java guy, but if I were answering, I'd offer that one does not mock classes one does not own. Therefore, just how do I (personally) mock MongoDB? I do not. Instead, I call Mongo (Java driver or Morphia) from my DAO layer, which is pretty thin anyway. I therefore mock my DAO layer. This works perfectly for me.

I use Mockito; I don't know what's available for C#, but I'll bet there are plenty of options.

Hope this helps,

Russ Bateman


On 11/7/2012 8:27 AM, Richard Byrne wrote:
I have a data layer that uses the C# MongoDB.Driver.

My data layer has a public MongoDatabase so I can inject a mock MongoDatabase for testing.

I'd like to test my datalayer by injecting a mock MongoDatabase and returning a mocked MongoCollection.

I've tried a number of ways to do this from the 2 or 3 suggestions made on the Web.
 
Latest version is adapted from http://thoai-nguyen.blogspot.com.au/2012/06/how-i-mock-mongo-collection.html  which mocks a collection and not a database

        [Test()]
        public void GetAllSettingsTest()
        {
            //Arrange
            MongoServerSettings ServerSettings;
            MongoServer Server;
            MongoDatabaseSettings DatabaseSettings;
            MongoDatabase Database;

            ServerSettings = new MongoServerSettings
            {
                Servers = new List<MongoServerAddress>
            {
                new MongoServerAddress("unittest")
            }
            };

            Server = new MongoServer(ServerSettings);
            DatabaseSettings = new MongoDatabaseSettings("databaseName", 
                                                        new MongoCredentials("", ""), 
                                                        GuidRepresentation.Standard, 
                                                        ReadPreference.Nearest, 
                                                        SafeMode.True);
            Database = new MongoDatabase(Server, DatabaseSettings);

            var collectionSetting = new MongoCollectionSettings<BsonDocument>(Database, typeof(BsonDocument).Name);
            var collection = new Mock<MongoCollection<BsonDocument>>(Database, collectionSetting);

            collection.Setup(f => f.Database).Returns(Database);
            collection.Setup(f => f.Settings).Returns(collectionSetting);

            BsonDocument doc01 = new BsonDocument();
            BsonDocument doc02 = new BsonDocument();
            collection.Object.Insert(doc01);
            collection.Object.Insert(doc02);

            var mongoDatabase = new Mock<MongoDatabase>(Server, DatabaseSettings);
            mongoDatabase.Setup(f => f.GetCollection(MongoCollections.Settings)).Returns(collection.Object);

            ILogger logger = new Logger();
            DatabaseClient.DatabaseClient target = new DatabaseClient.DatabaseClient(logger);
            target.MongoDatabase = mongoDatabase.Object;

            //Act
            List<BsonDocument> resultList =  target.GetAllSettings();
        }

At the line  target.MongoDatabase = mongoDatabase.Object; I'm getting a TargetInvocationException which is coming from the Object of the mock.
I'm thinking this is a problem with constructing the object even though I have supplied the parameter objects.

Anyone know what I'm doing wrong or a better way to do this?

The method I'm testing is:

        public List<BsonDocument> GetAllSettings()
        {
            var collection = MongoDatabase.GetCollection<BsonDocument>(MongoCollections.Settings);
            var query = from e in collection.AsQueryable()
                        select e;

            var settings = query.ToList();
            return settings;
        }
 
--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Richard Byrne

unread,
Nov 8, 2012, 6:32:34 AM11/8/12
to mongod...@googlegroups.com
It's the DAO layer I'm testing.

Russell Bateman

unread,
Nov 8, 2012, 10:02:12 AM11/8/12
to mongod...@googlegroups.com
I haven't found a way to unit-test my DAO layer, though I've looked for one. I've seen a couple of in-memory databases that could, in theory, take the place of MySQL, PostgreSQL, etc. in a unit test environment, but I've found the solution far too complicated. I once solicited help in this forum for a solution, but no one has come forward.

Best of luck; I'll be watching for an answer. Maybe we'll get one.

Russ

Rajnikant Rana

unread,
Aug 16, 2017, 8:43:30 AM8/16/17
to mongodb-user, ru...@windofkeltia.com
Hi Russ,

do you find any way for, how to mock MongoDB collection?

Rajnikant Rana

unread,
Aug 17, 2017, 12:54:44 AM8/17/17
to Russell Bateman, mongodb-user
Hi Russell,

Thank you for your prompt reply.

I achieved it the same way using mock library to return the stubbed result.

In MongoDB for c# driver, there are two version of Find() method.
1. using LINQ expression
2. using FilterDefinition

For LINQ expression, I developed the proper mock and working fine, but for FilterDefinition, I was not able to mock it properly. But anyway I developed one more wrapper and created mock of it and returned the in memory full List instead.

Hope you are now clear on my particular question or let me know if any better solution


Best Regards
Rajni 


On Wed, Aug 16, 2017 at 7:17 PM, Russell Bateman <ru...@windofkeltia.com> wrote:

You mean you're writing unit tests for your database code: You write your own DAO layer to accommodate alternate testing such that nothing reaches MongoDB, no MongoDB connection need actually be set up, and canned (stubbed) responses are returned that you can verify. The purpose is to test your code, not MongoDB. Leave off testing your database to integration testing.

Reply all
Reply to author
Forward
0 new messages