public void UriDeserializationNegative() { List<Tuple<string, string>> testCases = new List<Tuple<string, string>>() { new Tuple<string, string>("{\"Uri\":5}", "Error converting value 5 to type 'System.Uri'. Path 'Uri', line 1, position 8."), new Tuple<string, string>("{\"Uri\":true}", "Error converting value True to type 'System.Uri'. Path 'Uri', line 1, position 11."), }; foreach (var testCase in testCases) { var input = testCase.Item1; var expectedError = testCase.Item2; UriType actual = new UriType(); Exception actualError = null; try { // Need to ensure that the type is registered as a table to force the id property check DefaultSerializer.SerializerSettings.ContractResolver.ResolveTableName(typeof(UriType)); DefaultSerializer.Deserialize(input, actual); } catch (Exception e) { actualError = e; } Assert.AreEqual(actualError.Message, expectedError); } }
public void UriDeserialization() { List<Tuple<UriType, string>> testCases = new List<Tuple<UriType, string>>() { new Tuple<UriType, string>(new UriType() { Uri = null }, "{}"), new Tuple<UriType, string>(new UriType() { Uri = null }, "{\"Uri\":null}"), new Tuple<UriType, string>(new UriType() { Uri = new Uri("I'm not a URI", UriKind.Relative) }, "{\"Uri\":\"I'm not a URI\"}"), new Tuple<UriType, string>(new UriType() { Uri = new Uri("\t", UriKind.Relative) }, "{\"Uri\":\"\t\"}"), new Tuple<UriType, string>(new UriType() { Uri = new Uri("ftp://127.0.0.1/") }, "{\"Uri\":\"ftp://127.0.0.1/\"}"), new Tuple<UriType, string>(new UriType() { Uri = new Uri("http://somehost/") }, "{\"Uri\":\"http://someHost\"}"), new Tuple<UriType, string>(new UriType() { Uri = new Uri("ftp://127.0.0.1/") }, "{\"Uri\":\"ftp://127.0.0.1/\"}"), }; // Need to ensure that the type is registered as a table to force the id property check DefaultSerializer.SerializerSettings.ContractResolver.ResolveTableName(typeof(UriType)); foreach (var testCase in testCases) { var input = JToken.Parse(testCase.Item2); var expected = testCase.Item1; UriType actual = new UriType(); DefaultSerializer.Deserialize(input, actual); Assert.AreEqual(actual.Uri, expected.Uri); if (testCase.Item2 != "{}") { actual = new UriType(); actual.Uri = new Uri("http://xyz.com"); DefaultSerializer.Deserialize(input, actual); } Assert.AreEqual(actual.Uri, expected.Uri); JArray json = JToken.Parse("[" + testCase.Item2 + "]") as JArray; actual = DefaultSerializer.Deserialize<UriType>(json).FirstOrDefault(); Assert.AreEqual(actual.Uri, expected.Uri); actual = (UriType)DefaultSerializer.Deserialize<UriType>(input); Assert.AreEqual(actual.Uri, expected.Uri); } }