简体   繁体   English

c#通用方法的单元测试

[英]c# Unit Testing for Generic method

I have to test the below generic method which is internal class of another assembly. 我必须测试下面的泛型方法,它是另一个程序集的内部类。

internal class JsonSerializationUtility
{ 
  public static string SerializeJson<T>(T obj) 
  { 
    string jsonFormattedString = string.Empty; 
    try { 
        MemoryStream memStreamObj = new MemoryStream();
        DataContractJsonSerializer jsonSerObj = new DataContractJsonSerializer(typeof(T)); 
        jsonSerObj.WriteObject(memStreamObj, obj); 
        memStreamObj.Position = 0; StreamReader sr = new StreamReader(memStreamObj); 
        jsonFormattedString = sr.ReadToEnd(); 
    }
    catch (Exception ex) { 
        Log.Error("Exception details: ", ex); 
    } 
  return jsonFormattedString; 
  }
}

and i have tried in this way: 我试过这样的方式:

[TestMethod]
public void SerializeJson() 
{ 
    PrivateType privateObj = new PrivateType(typeof(JsonSerializationUtility)); 
    string input= "WorldCup2015"; 
    string output = privateObj.InvokeStatic("SerializeJson<objectType>", input).ToString(); 
    Assert.IsNotNull(output); 
}

But i am getting the missing method reference. 但我得到了缺少的方法参考。 Can anyone suggest how should have to test for Generic method. 任何人都可以建议如何测试Generic方法。

I had done same procedure of writing test code for simple static method, but unable for generic method. 我为简单的静态方法编写了相同的编写测试代码的过程,但是无法使用泛型方法。

我测试internal类的首选解决方案是使用InternalsVisibleToAttribute

You're using the wrong overload. 你使用了错误的重载。

Use PrivateType.InvokeStatic Method (String, Type[], Object[], Type[]) to invoke a generic method. 使用PrivateType.InvokeStatic Method (String, Type[], Object[], Type[])来调用泛型方法。

Note that I, too, would use [assembly: InternalsVisibleTo("TestProject")] . 请注意,我也会使用[assembly: InternalsVisibleTo("TestProject")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM