2016-11-28 77 views
1

我想對一個單元測試來返回任務的頂線嘲笑ReadAsStringAsync其中字符串是下面的JSON:轉換有效的JSON的任務<string>

var jsonString = await response.Content.ReadAsStringAsync(); 
// convert to our OfferJsonRow format 
var jsonData = JsonConvert.DeserializeObject<Dictionary<string, List<OfferJsonRow>>>(jsonString); 
var rawOfferData = jsonData["data"]; 

如何轉換這種有效JSON到Task<string>

JSON:

{ 
    "data": [{ 
     "Latitude": "xxx", 
     "RedemptionType": "barcode", 
     "Version": "1", 
     "HeaderType": "", 
     "FontColour": "", 
     "LogoType": "", 
     "RedemptionLimit": "", 
     "RedemptionTimeMinutes": "" 
    }] 
} 

這裏是我的代碼:

var response = new Mock<HttpResponseMessage>(); 
response.Setup(rm => rm.Content.ReadAsStringAsync()).Returns(Task.Delay(10).ContinueWith(t => "Hello")); 

我相信,如果我取代「你好」與JSON那麼這將是我想要什麼,但粘貼時,它拋出錯誤是JSON到Visual Studio代碼

+0

在粘貼時,你可能無法逃脫的報價,將是我的猜先 – Rob

+0

@Rob呀。所以這是必要的? – BeniaminoBaggins

+0

您需要返回任務''而是返回'Task'我的JSON實際上是巨大的,比我這裏輸入要大得多。您可以嘗試返回'Task.FromResult(「你好」);' – Fabio

回答

0

由於意見建議,我不得不逃離JSON最初只是爲了得到視覺工作室接受它。例如:

var JSONString = ""Longitude"": ""xxx"", 
      ""Latitude"": ""-xxx"", 
      ""RedemptionType"": ""barcode"", 
      ""Version"": ""1"", 
      ""HeaderType"": """", 
      ""FontColour"": """", 
      ""LogoType"": """", 
      ""RedemptionLimit"": """", 
      ""RedemptionTimeMinutes"": """" 
     }] 
    }"; 

然後使用它作爲一個JSON字符串,客戶端代碼預期,我不得不取消轉義它:

var unescapedjson = Regex.Unescape(JSONString); 

至於Task<string>,它成爲不必要的嘲笑HttpResponseMessage所以不需要。

我用了一個真正的HttpResponseMessage並手動設置其contentunescapedjson

var response = new HttpResponseMessage(); 
Microsoft.JScript.GlobalObject.unescape(JSONString); 
response.Content = new StringContent(unescapedjson); 

全碼:

[Test] 
public async Task AllPartners_HasPartners_GetsThem() { 
var response = new HttpResponseMessage(); 
var unescapedjson = Regex.Unescape(JSONString); 
var unescapedjson2 = Microsoft.JScript.GlobalObject.unescape(JSONString); 
response.Content = new StringContent(unescapedjson); 
await _offersDataService.ProcessResponse(response); 
Assert.Greater(_offersDataService.AllPartners.Count, 0); 
} 
相關問題