Created
November 10, 2012 02:31
-
-
Save pauldotknopf/4049602 to your computer and use it in GitHub Desktop.
Unit testing with mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using(new MongoScope("9999")) | |
{ | |
const string connectionString = "mongodb://localhost:9999/?safe=true"; | |
var server = MongoServer.Create(connectionString); | |
var blog = server.GetDatabase("blog"); | |
var posts = blog.GetCollection<Post>("posts"); | |
var firstPost = new Post(); | |
firstPost.Content = "This is the first post on my very popular blog."; | |
firstPost.Id = Guid.NewGuid().ToString(); | |
posts.Save(firstPost); | |
var query = Query.EQ("Content", "This is the first post on my very popular blog."); | |
foreach (var matchingPost in posts.Find(query)) | |
{ | |
Console.WriteLine(matchingPost.Content); | |
} | |
} | |
Console.ReadLine(); | |
} | |
public class Post | |
{ | |
public string Id { get; set; } | |
public string Content { get; set; } | |
} | |
} | |
public class MongoScope : IDisposable | |
{ | |
private Process _process = null; | |
public MongoScope(string port) | |
{ | |
var testDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MongoDB"); | |
if (Directory.Exists(testDirectory)) | |
Directory.Delete(testDirectory, true); | |
Directory.CreateDirectory(testDirectory); | |
_process = Process.Start(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mongod.exe"), "--dbpath \"" + testDirectory + "\" --port \"" + port + "\""); | |
} | |
public void Dispose() | |
{ | |
_process.Kill(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment