Unit testing 如何提供字符串形式的ObjectContent

Unit testing 如何提供字符串形式的ObjectContent,unit-testing,asp.net-web-api,Unit Testing,Asp.net Web Api,我正在编写一个单元测试,它测试在请求中发送一个实体的场景,该请求是一个普通字符串,即不可解析为JSON 在这个测试中,我将HttpRequestMessage设置如下: var ojectContent = new ObjectContent(typeof(string) , "aaaaa" , new JsonMediaTypeFormatter()); httpRequestMessage.Con

我正在编写一个单元测试,它测试在请求中发送一个实体的场景,该请求是一个普通字符串,即不可解析为JSON

在这个测试中,我将
HttpRequestMessage
设置如下:

var ojectContent = new ObjectContent(typeof(string)
                        , "aaaaa"
                        , new JsonMediaTypeFormatter());
httpRequestMessage.Content = objectContent;
objectContent = new ObjectContent(typeof(string)
                        , "not json"
                        , new DoNothingTypeFormatter());
问题是,当我调试代码时,请求主体被设置为
“aaaaa”
(注意附加的引号),这足以导致反序列化代码以不同的方式对待请求主体,这意味着我无法测试我要测试的内容。我需要请求主体为
aaaaaaa

有谁能建议我如何设置测试,以便请求主体不包含这些引用


编辑:我还尝试了
新的ObjectContent(typeof(object)…
,它给出了相同的结果。

好的,所以我需要创建一个媒体类型格式化程序,它不会以任何方式干扰输入。我使用了以下方法:

private class DoNothingTypeFormatter : MediaTypeFormatter
        {
            public override bool CanReadType(Type type)
            {
                return false;
            }

            public override bool CanWriteType(Type type)
            {
                if (type == typeof(string))
                {
                    return true;
                }

                return false;
            }

            public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
            {
                var myString = value as string;
                if (myString == null)
                {
                    throw new Exception("Everything is supposed to be a string here.");
                }

                var length = myString.Length;
                var bytes = System.Text.Encoding.UTF8.GetBytes(myString);

                return Task.Factory.StartNew(() => writeStream.Write(bytes, 0, length));
            }
        }
然后,当我想生成“HttpRequestMessage”的主体时,我会这样做:

var ojectContent = new ObjectContent(typeof(string)
                        , "aaaaa"
                        , new JsonMediaTypeFormatter());
httpRequestMessage.Content = objectContent;
objectContent = new ObjectContent(typeof(string)
                        , "not json"
                        , new DoNothingTypeFormatter());

另一种方法是通过使用
StringContent
而不是
ObjectContent
绕过
MediaTypeFormatter

 var content = new StringContent("aaaaa");
 httpRequestMessage.Content = content;