Skip to content

Commit 19e0715

Browse files
authored
CSHARP-5007: Better error when no matching constructor found (#406)
1 parent 2803f87 commit 19e0715

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/MongoDB.Bson/Serialization/Serializers/BsonClassMapSerializer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ private BsonCreatorMap ChooseBestCreator(Dictionary<string, object> values)
414414

415415
if (creatorMap == null)
416416
{
417-
throw new BsonSerializationException("No matching creator found.");
417+
throw new BsonSerializationException($"No matching creator found for class {_classMap.ClassType.FullName}.");
418418
}
419419

420420
return creatorMap;

tests/MongoDB.Bson.Tests/Serialization/BsonClassMapSerializerTests.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,42 @@ public void Deserialize_should_throw_invalidOperationException_when_creator_retu
3939
exception.Should().BeOfType<BsonSerializationException>();
4040
}
4141

42+
[Fact]
43+
public void Deserialize_should_throw_when_no_creators_found()
44+
{
45+
var bsonClassMap = new BsonClassMap<ModelWithCtor>();
46+
bsonClassMap.AutoMap();
47+
bsonClassMap.Freeze();
48+
49+
var subject = new BsonClassMapSerializer<ModelWithCtor>(bsonClassMap);
50+
51+
using var reader = new JsonReader("{ \"_id\": \"just_an_id\" }");
52+
var context = BsonDeserializationContext.CreateRoot(reader);
53+
54+
var exception = Record.Exception(() => subject.Deserialize(context));
55+
exception.Should().BeOfType<BsonSerializationException>()
56+
.Subject.Message.Should().Be($"No matching creator found for class {typeof(ModelWithCtor).FullName}.");
57+
}
58+
4259
// nested classes
4360
private class MyModel
4461
{
4562
public string Id { get; set; }
4663
}
64+
65+
private class ModelWithCtor
66+
{
67+
private readonly string _myId;
68+
private readonly int _i;
69+
70+
public ModelWithCtor(string id, int i)
71+
{
72+
_myId = id;
73+
_i = i;
74+
}
75+
76+
public string Id => _myId;
77+
public int I => _i;
78+
}
4779
}
4880
}

0 commit comments

Comments
 (0)