-
-
Save dtchepak/36271ec17dc6aee8e50cd21ff24a09b3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using MongoDB.Bson; | |
using MongoDB.Driver; | |
using NSubstitute; | |
using NSubstitute.ExceptionExtensions; | |
using Xunit; | |
namespace NSubWorkshop | |
{ | |
public class ComponentRecordDataModel | |
{ | |
public string Id { get; set; } | |
public List<string> UserViews { get; set; } = new List<string>(); | |
} | |
public interface IMongoContext { | |
IEnumerable<T> Find<T>(FilterDefinition<T> filter, ProjectionDefinition<T> projection); | |
} | |
public class SampleClass | |
{ | |
IMongoContext MongoContext; | |
public SampleClass(IMongoContext context) | |
{ | |
this.MongoContext = context; | |
} | |
public ComponentRecordDataModel GetRecordUserViews(string id) | |
{ | |
var filter = Builders<ComponentRecordDataModel>.Filter.Eq(x => x.Id, id); | |
var projection = Builders<ComponentRecordDataModel>.Projection.Include(x => x.UserViews); | |
var result = MongoContext.Find(filter, projection).FirstOrDefault(); | |
return result; | |
} | |
} | |
public class DataAccessException : Exception {} | |
public class MongoTest | |
{ | |
[Fact] | |
public void LogsExceptionWhenOnGetRecordUserViews() | |
{ | |
var _exception = new DataAccessException(); | |
var _recordModel = new ComponentRecordDataModel { Id = "123", UserViews = { "a", "b" } }; | |
var _mongoContext = Substitute.For<IMongoContext>(); | |
var _collection = new SampleClass(_mongoContext); | |
var filter = Builders<ComponentRecordDataModel>.Filter.Eq(x => x.Id, _recordModel.Id); | |
var projection = Builders<ComponentRecordDataModel>.Projection.Include(x => x.UserViews); | |
var expectedFilter = Arg.Is<FilterDefinition<ComponentRecordDataModel>>( | |
x => ToJson(x).Equals(ToJson(filter))); | |
var expectedProjection = Arg.Is<ProjectionDefinition<ComponentRecordDataModel>>( | |
x => ToJson(x).Equals(ToJson(projection))); | |
_mongoContext.Find(expectedFilter, expectedProjection).Throws(_exception); | |
Assert.Throws(typeof(DataAccessException), () => _collection.GetRecordUserViews(_recordModel.Id)); | |
} | |
static string ToJson<T>(T t) | |
{ | |
// Avoiding Error CS0854: An expression tree may not contain a call or invocation that uses optional arguments | |
return t.ToJson(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment