模拟行为严格

时间:2016-07-26 00:50:02

标签: c# unit-testing moq

我是Moq框架的新手,我有一个测试方法,但我收到以下错误。我无法找到错过的地方。

有人可以告诉我如何更正以下错误?

  

类型' 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();
}

1 个答案:

答案 0 :(得分:5)

您创建了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