Comments (5)
Hi there, the shown example looks fine. But there should be no need to clean up things on your own. Just call again MongoDbRunner.Start()
in the next test again and you well get a fresh and empty MongoDB instance which has an own network port and works in its own directory. Instances can run in parallel. That's the idea behind Mongo2Go.
Don't forget to dispose (either by calling it or via the using
statement), because the test runner might kill the process and things could be non deterministic in that case!
from mongo2go.
I am not using xUnit specifically, but I did set something like this up with NUnit just recently. It's definitely a first pass. So there could be better ways to set this up. But looking over the example on the docs (https://github.com/Mongo2Go/Mongo2Go#examples) I don't think it's too far off.
My strategy has been this:
First, I wrote a static setup fixture that runs when integration tests are started up and torn down at the end of the suite. I expose all of these properties because I didn't know or want to limit what I could do when setting up. Some places require certain info (like a Context
object may want access to the Database
instance for example). You could go the singleton route with this, but I felt like static properties were good enough to get me going.
using NUnit.Framework;
using MongoDB.Driver;
using Mongo2Go;
namespace Tests.Repositories
{
[SetUpFixture]
[Category("Integration")]
public class IntegrationDb
{
public static MongoDbRunner Runner { get { return _runner; } }
public static MongoClient Client { get { return _client; } }
public static IMongoDatabase Database { get { return _fakeDb; } }
private static MongoDbRunner _runner;
private static MongoClient _client;
private static IMongoDatabase _fakeDb;
[OneTimeSetUp]
public void InitIntegrationTests()
{
_runner = MongoDbRunner.Start();
_client = new MongoClient(_runner.ConnectionString);
_fakeDb = _client.GetDatabase("IntegrationTestDb");
}
[OneTimeTearDown]
public void TeardownIntegrationTests()
{
_runner.Dispose();
_runner = null;
_client = null;
_fakeDb = null;
}
}
}
Next, Each integration fixture then performs a single setup and teardown step when the database is populated and then cleared out for a suite. In the beginning I was clearing the DB on each test in a fixture. This worked fine and could be used if individual tests need very specific setups, but I found that it made the tests a little slower than I wanted.
namespace Tests.Repositories
{
[TestFixture]
[Category("Integration")]
public class MyRepositoryTests
{
[OneTimeSetUp]
public void Init()
{
this.ClearTheDatabase();
this.InsertTestData(IntegrationDb.Database);
Repository = new MyRepository(new FakeContext(IntegrationDb.Database));
}
[OneTimeTearDown]
public void Teardown()
{
this.ClearTheDatabase();
}
}
}
Lastly, it's really just a matter of building pretty typical tests you might see with NUnit.
[Test]
public async Task Find_Null_When_No_Entry_With_Id_Found()
{
var actual = Repository.FindAsync("a-fake-id");
Assert.That(actual, Is.Null);
}
So far I've used this for two of the Repository classes I've been testing and have had good luck. So not a ton of mileage yet, but it's something at least!
from mongo2go.
Thanks, will try this approach again.
from mongo2go.
Hi,
I am struggling on how to call the dispose on my MongoDbRunner and I've noticed many "Mongo DB Server" processed are running on task manager. The tests are really unpredictable. This is my setup:
I have this TestStartup which overwrites the database configuration:
public class TestStartup : Startup
{
public TestStartup(IConfiguration configuration)
: base(configuration)
{
}
public override void ConfigureDatabase(ContainerBuilder builder)
{
builder
.Register(context =>
{
var mongoDbRunner = MongoDbRunner.Start();
//var mongoDbRunner = MongoDbRunner.StartForDebugging(port: 27020); // use when debugging
return new MongoClient(mongoDbRunner.ConnectionString).GetDatabase("IntegrationTestDb");
})
.As<IMongoDatabase>()
.InstancePerDependency();
}
}
And one of my tests looks like that:
public class GroupsControllerTests
{
private IRepository<GroupSettings, Guid> repository;
private readonly TestServer server;
private readonly HttpClient client;
public GroupsControllerTests()
{
server = new TestServer(new WebHostBuilder()
.ConfigureServices(services => services.AddAutofac())
.UseStartup<TestStartup>()
.UseEnvironment("Development"));
client = server.CreateClient();
}
[Fact]
public async Task Put_GroupSettingsUpdated_ReturnsGroupSettingsResponse()
{
string groupId = "5a0ca47e23a5731a98151bbe";
var request = new Fixture().Create<GroupSettingsRequest>();
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PutAsync(string.Format("api/v1/groups/{0}/settings", groupId), content);
response.EnsureSuccessStatusCode(); // Status Code 200-299
var settingsResponse = JsonConvert.DeserializeObject<GroupSettingsResponse>(await response.Content.ReadAsStringAsync());
Assert.True(settingsResponse.IsEnabled);
Assert.Equal(groupId, settingsResponse.GroupId);
Assert.Equal(request.Settings, settingsResponse.Settings);
}
}
Any ideas?
from mongo2go.
I found a solution for my problem. Updated my TestStartup to this
public class TestStartup : Startup
{
public TestStartup(IConfiguration configuration)
: base(configuration)
{
}
public override void ConfigureDatabase(ContainerBuilder builder)
{
builder.Register(context => MongoDbRunner.Start())
.As<MongoDbRunner>()
.SingleInstance();
builder
.Register(context =>
{
var mongoDbRunner = context.Resolve<MongoDbRunner>();
//var mongoDbRunner = MongoDbRunner.StartForDebugging(port: 27020); // use when debugging
return new MongoClient(mongoDbRunner.ConnectionString).GetDatabase("IntegrationTestDb");
})
.As<IMongoDatabase>()
.SingleInstance();
}
}
Added IDisposable to my test class and did this
public void Dispose()
{
client.Dispose();
server.Dispose();
}
no process hanging on Task Manager anymore. Hope it helps someone.
Thanks
from mongo2go.
Related Issues (20)
- Using MongoRunner in a singletone DbContext
- Changing the default nuget cache folder breaks binary search HOT 5
- Arm64 support HOT 7
- SingleNodeReplSet hangs during the Azure's pipeline's tests HOT 2
- Issue when running in Alpine build container HOT 16
- Upgrade MongoDb to latest stable version 5.x HOT 2
- NuGet package size concerns HOT 8
- Cannot find MongoDB binaries by default on Ubuntu 18.04 LTS (Bionic Beaver) / Azure DevOps Linux build agent HOT 7
- Mongo2Go 3.X.X Not working in GitlabCI HOT 5
- Thousands of empty directories HOT 2
- Install failed. Access to the path 'mongodb.exe' is denied.
- Error in $lookup using localField e ForeingField HOT 1
- Wrong home folder is used on Linux HOT 1
- Alternative to Mongo2Go HOT 2
- Getting error in CI pipeline in the github action HOT 4
- MongoCommandException thrown when setting the SeverApi in MongoClientSettings HOT 1
- Too many open files
- Does Mongo2Go supports queries with $regex?
- Missing libcrypto.so.1.1 in mcr.microsoft.com/dotnet/sdk:8.0 HOT 4
- Is possible to create nuget with MongoDB.Driver.signed?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mongo2go.