2013-07-02 54 views
1

嗨我已經創建了一個包裝器在JavascriptSerializer能夠moq這一點。嘲笑JavascriptSerializer導致錯誤

這是我的代碼:

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

現在在我的單元測試,我已經tryed嘲笑這是這樣的:

private Mock<IJavascriptSerializerWrapper> m_JavascriptSerializerWrapper; 

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

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

我已經調試單元測試,我得到這個錯誤:

Invalid setup on a non-virtual (overridable in VB) member: x => x.GetJavascriptSerializer().Serialize(.userInfoDTO)

我在做什麼錯在這裏,我該如何解決這個問題?

回答

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
x.GetJavascriptSerializer().Serialize(userInfoDTO) 

所以你不只是想嘲笑 'IJavascriptSerializerWrapper' 也是JavascriptSerializer本身

你想要的是這樣的:

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