Giter Site home page Giter Site logo

Comments (5)

JohannesHoppe avatar JohannesHoppe commented on May 8, 2024 2

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.

pseudoramble avatar pseudoramble commented on May 8, 2024

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.

borysr avatar borysr commented on May 8, 2024

Thanks, will try this approach again.

from mongo2go.

renatogbp avatar renatogbp commented on May 8, 2024

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.

renatogbp avatar renatogbp commented on May 8, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.