我有以下两个单元测试:一个使用 MSTest,另一个使用机器规格。据我所知,它们的行为应该相同。但是,虽然第一个在 NCrunch 和 ReSharper 测试运行程序中都通过了,但第二个在 ReSharper 中失败了。
using Machine.Specifications;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
public class TestModel
{
public string Name { get; set; }
public int Number { get; set; }
}
// MSTest
[TestClass]
public class DeserializationTest
{
[TestMethod]
public void Deserialized_object_is_the_same_type_as_the_original()
{
TestModel testModel = new TestModel() {Name = "John", Number = 42};
string serialized = JsonConvert.SerializeObject(testModel, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
object deserialized = JsonConvert.DeserializeObject(serialized, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
// This passes in both test runners
Assert.IsInstanceOfType(deserialized, typeof(TestModel));
}
}
// MSpec
public class When_an_object_is_deserialized
{
static TestModel testModel;
static string serialized;
static object deserialized;
Establish context = () =>
{
testModel = new TestModel() { Name = "John", Number = 42 };
serialized = JsonConvert.SerializeObject(testModel, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
};
Because of = () => deserialized = JsonConvert.DeserializeObject(serialized, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
// This passes in NCrunch but fails in ReSharper.
It should_be_the_same_type_as_the_original = () => Assert.IsInstanceOfType(deserialized, typeof(TestModel));
}
失败消息是:Assert.IsInstanceOfType failed. Expected type:<UnitTestProject2.TestModel>. Actual type:<UnitTestProject2.TestModel>.
奇怪的是,以下确实通过了:
It should_be_the_same_type_as_the_original = () => Assert.IsTrue(testModel.GetType() == typeof(TestModel));
我正在以这种方式进行反序列化,因为有问题的实际代码需要能够处理其类型在运行时之前未知的对象。我认为 Json.NET 进行这种反序列化的方式有些奇怪,但是为什么两个测试运行器的行为会有所不同呢?我在 Visual Studio 2013 中使用 ReSharper 9.1。