2016-07-26 58 views
1

我是新來的Moq框架,我有一個測試方法的書寫,但我得到下面的錯誤。我找不到我錯過的地方。Moq.Mock異常與調用失敗與模擬行爲嚴格

有人可以讓我知道如何糾正下面的錯誤?


類型的異常「Moq.MockException」發生在Moq.dll但 在用戶代碼中處理

附加信息:IResponseMessage.ReadContentAsString() 調用失敗,仿製品的行爲嚴格。

模擬上的所有調用必須有相應的設置。

Execp.cs

public Execp(IResponseMessage msg) 
{ 

    this.StatusCode = msg.StatusCode;//*getting exception here while running **method 1*** 
    this.ReadContentAsString = msg.ReadContentAsString();//*getting exception here while running **method 2*** 


} 

我的測試方法

方法1

[TestMethod()]   
public void TestFail() 
{ 

    int employeeId = 0; 

    DataModel.Employee.Get.Employee employee= new DataModel.Employee.Get.Employee(); 
    string url = string.Format("api/1/somename/{0}", employeeId); 

    restClient 
     .Setup(x => x.Get(url)) 
     .Returns(responseMessage.Object); 

    responseMessage.SetupGet(x => x.IsSuccessStatusCode).Returns(false); 

    var client = new account(clientFactory.Object, serverUri, moqLogged.Object); 
    var result = client.GetEmployee(employeeId); 
    Assert.AreEqual(result, null); 

    client.Dispose(); 
    moqFactory.VerifyAll(); 
} 

方法2

[TestMethod()] 
public void TestBadRequest() 
{ 

    var httpStatusCode = System.Net.HttpStatusCode.BadRequest; 

    string employeeName = "Test Name"; 
    int teamLeaderId= 1; 
    string url = string.Format("api/1/somename/{0}/teammember", teamLeaderId); 
    DataModel.Group.Post.TeamMember employee= new DataModel.Group.Post.teamMember(); 

    UserResponse userResponse = new UserResponse(); 

    restClient 
     .Setup(x => x.PostAsJson(url, It.IsAny<DataModel.Employee.Post.TeamMember>())) 
     .Returns(responseMessage.Object); 

    responseMessage.SetupGet(x => x.IsSuccessStatusCode).Returns(false); 
    responseMessage.SetupGet(x => x.StatusCode).Returns(httpStatusCode); 

    var client = new AcronisAccountManagementClient(clientFactory.Object, serverUri, moqLogged.Object); 

    var result = client.CreateEmployee(employee, teamLeaderId); 
    Assert.AreEqual(result.statusCode, httpStatusCode); 

    client.Dispose(); 
    moqFactory.VerifyAll(); 
} 

回答

2

您創建了一個Mock<IResponseMessage>,默認情況下它

MockBehavior.Strict使用MockBehavior.Strict:使模擬將始終拋出調用一個異常 沒有相應的設置。

在代碼中的某處,您正在調用沒有設置配置的成員。我建議在你的測試

對於方法1和2創建你打算調用所有成員設置:

//...other code removed for brevity 

var httpStatusCode = System.Net.HttpStatusCode.BadRequest;//or what ever you want it to be 
responseMessage.Setup(m => m.StatusCode).Returns(httpStatusCode); 
responseMessage.Setup(m => m.ReadContentAsString()).Returns("Put your return string here"); 

//...other code removed for brevity 
+0

你是最好的。謝謝。 – crony

相關問題