You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

83 lines
2.7 KiB

  1. using System;
  2. using FluentAssertions;
  3. using MongoDB.Bson;
  4. using MongoDB.Driver;
  5. using Xunit;
  6. namespace DotNetCore.CAP.MongoDB.Test
  7. {
  8. public class MongoDBTest
  9. {
  10. private MongoClient _client;
  11. public MongoDBTest()
  12. {
  13. _client = new MongoClient(ConnectionUtil.ConnectionString);
  14. }
  15. [Fact]
  16. public void MongoDB_Connection_Test()
  17. {
  18. var names = _client.ListDatabaseNames();
  19. names.ToList().Should().NotBeNullOrEmpty();
  20. }
  21. [Fact]
  22. public void Transaction_Test()
  23. {
  24. var document = new BsonDocument
  25. {
  26. { "name", "MongoDB" },
  27. { "type", "Database" },
  28. { "count", 1 },
  29. { "info", new BsonDocument
  30. {
  31. { "x", 203 },
  32. { "y", 102 }
  33. }}
  34. };
  35. var db = _client.GetDatabase("test");
  36. var collection1 = db.GetCollection<BsonDocument>("test1");
  37. var collection2 = db.GetCollection<BsonDocument>("test2");
  38. using (var sesstion = _client.StartSession())
  39. {
  40. sesstion.StartTransaction();
  41. collection1.InsertOne(document);
  42. collection2.InsertOne(document);
  43. sesstion.CommitTransaction();
  44. }
  45. var filter = new BsonDocument("name", "MongoDB");
  46. collection1.CountDocuments(filter).Should().BeGreaterThan(0);
  47. collection2.CountDocuments(filter).Should().BeGreaterThan(0);
  48. }
  49. [Fact]
  50. public void Transaction_Rollback_Test()
  51. {
  52. var document = new BsonDocument
  53. {
  54. {"name", "MongoDB"},
  55. {"date", DateTimeOffset.Now.ToString()}
  56. };
  57. var db = _client.GetDatabase("test");
  58. var collection = db.GetCollection<BsonDocument>("test3");
  59. var collection4 = db.GetCollection<BsonDocument>("test4");
  60. using (var session = _client.StartSession())
  61. {
  62. session.IsInTransaction.Should().BeFalse();
  63. session.StartTransaction();
  64. session.IsInTransaction.Should().BeTrue();
  65. collection.InsertOne(session, document);
  66. collection4.InsertOne(session, new BsonDocument { { "name", "MongoDB" } });
  67. session.AbortTransaction();
  68. }
  69. var filter = new BsonDocument("name", "MongoDB");
  70. collection.CountDocuments(filter).Should().Be(0);
  71. collection4.CountDocuments(filter).Should().Be(0);
  72. }
  73. }
  74. }