Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json.Tests\Serialization\ConstructorHandlingTests.cs

Symbol Coverage: 88.24% (15 of 17)

Branch Coverage: 60.00% (3 of 5)

Cyclomatic Complexity Avg: 1.00 Max:1

Code Lines: 25


L V Source
1
using System.Collections.Generic;
2
using System.Linq;
3
using System.Reflection;
4
using System.Text;
5
using Newtonsoft.Json.Tests.TestObjects;
6
using NUnit.Framework;
7

  
8
namespace Newtonsoft.Json.Tests.Serialization
9
{
10
  public class ConstructorHandlingTests : TestFixtureBase
11
  {
12
    [Test]
13
    [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.PrivateConstructorTestClass. A class should either have a default constructor or only one constructor with arguments.")]
14
    public void FailWithPrivateConstructorAndDefault()
15
    {
16
 1
      string json = @"{Name:""Name!""}";
17

  
18
 1
      JsonConvert.DeserializeObject<PrivateConstructorTestClass>(json);
19
 0
    }
20

  
21
    [Test]
22
    public void SuccessWithPrivateConstructorAndAllowNonPublic()
23
    {
24
 1
      string json = @"{Name:""Name!""}";
25

  
26
 1
      PrivateConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorTestClass>(json,
27
 1
        new JsonSerializerSettings
28
 1
          {
29
 1
            ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
30
 1
          });
31
 1
      Assert.IsNotNull(c);
32
 1
      Assert.AreEqual("Name!", c.Name);
33
 1
    }
34

  
35
    [Test]
36
    [ExpectedException(typeof(TargetInvocationException))]
37
    public void FailWithPrivateConstructorPlusParametizedAndDefault()
38
    {
39
 1
      string json = @"{Name:""Name!""}";
40

  
41
 1
      PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
42
 0
    }
43

  
44
    [Test]
45
    public void SuccessWithPrivateConstructorPlusParametizedAndAllowNonPublic()
46
    {
47
 1
      string json = @"{Name:""Name!""}";
48

  
49
 1
      PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json,
50
 1
        new JsonSerializerSettings
51
 1
        {
52
 1
          ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
53
 1
        });
54
 1
      Assert.IsNotNull(c);
55
 1
      Assert.AreEqual("Name!", c.Name);
56
 1
      Assert.AreEqual(1, c.Age);
57
 1
    }
58
  }
59
}