2014-07-15 18 views
1

我正在編寫一個單元測試,它測試在請求中發送正文的場景,該請求是一個純字符串,即不能解析爲JSON。如何提供字符串的ObjectContent

在這個測試中,我設置HttpRequestMessage是這樣的:

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

問題是,當我調試代碼,請求體已經被設置爲"aaaaa"(注意額外的報價)的足以導致反序列化代碼以不同的方式處理請求體,這意味着我無法測試我的意思來測試。我需要請求機構aaaaa

任何人都可以建議如何設置測試,以便請求正文不包含這些引號?

編輯:我也試過new ObjectContent(typeof(object)...,它給出了相同的結果。

回答

1

另一種方法是使用StringContent,而不是繞過MediaTypeFormatterObjectContent

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

好多了。 – David

-1

好的,所以我需要創建一個不會以任何方式干擾輸入的媒體類型格式化程序。我用這個:

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」身上,我這樣做是這樣的:

objectContent = new ObjectContent(typeof(string) 
         , "not json" 
         , new DoNothingTypeFormatter()); 
+0

哎唷!爲downvote。 – David

相關問題