模拟JavascriptSerializer会导致错误

时间:2013-07-02 12:13:57

标签: c# unit-testing moq

您好我已经在JavascriptSerializer上创建了一个包装器,以便能够进行此操作。

这是我的代码:

public class JavascriptSerializerWrapper : IJavascriptSerializerWrapper
{
    public JavaScriptSerializer GetJavascriptSerializer()
    {
        return new JavaScriptSerializer();
    }
}

现在在我的单元测试中,我试图像这样嘲笑:

    private Mock<IJavascriptSerializerWrapper> m_JavascriptSerializerWrapper;

    [TestInitialize]
    public void Initializer()
    {
        m_JavascriptSerializerWrapper = new Mock<IJavascriptSerializerWrapper>();
    }

    [TestMethod]
    public void Login_IsValidUser_ReturnsTrue()
    {
        const string serializedObject = "{\"EmailAddress\":\"kimmiem30@hotmail.com123\",\"StudentId\":1200528,\"TeacherId\":null,\"EmployeeId\":null,\"PersonId\":82249,\"MessageUserId\":410335}";
         m_JavascriptSerializerWrapper.Setup(x => x.GetJavascriptSerializer().Serialize(userInfoDTO)).Returns(serializedObject);
    }

我调试了单元测试,我收到了这个错误:

  

非虚拟(VB中可覆盖)成员的设置无效:x =&gt; x.GetJavascriptSerializer()。序列化(.userInfoDTO)

我在这里做错了什么,如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

JavaScriptSerializer.Serialize不是虚拟的,所以不能被嘲笑。相反,您的包装器接口和类应该包含一个可以模拟的Serialize方法。

例如:

public class JavascriptSerializerWrapper : IJavascriptSerializerWrapper
{
    public string Serialize(object toSerialize)
    {
        var serializer = new JavaScriptSerializer();
        return serializer.Serialize(toSerialize);
    }
}

然后您的测试可以像这样使用它:

m_JavascriptSerializerWrapper.Setup(x => x.Serialize(userInfoDTO)).Returns(serializedObject);

答案 1 :(得分:1)

x.GetJavascriptSerializer().Serialize(userInfoDTO)

所以你不只是试图模仿'IJavascriptSerializerWrapper'而且还试图模仿JavascriptSerializer本身

你想要的是:

public class JavascriptSerializerWrapper : IJavascriptSerializerWrapper
{
    private JavascriptSerializer _serializer = new JavascriptSerializer();
    public JavaScriptSerializer Serialize()
    {
        return _serializer.Serialize();
    }
}