带有调用的Moq.Mock异常因模拟行为严格而失败

cro*_*ony 9 c# unit-testing moq

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

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


Moq.dll中出现"Moq.MockException"类型的异常,但未在用户代码中处理

其他信息:IResponseMessage.ReadContentAsString()调用失败,模拟行为Strict.

模拟上的所有调用都必须具有相应的设置.

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***


}
Run Code Online (Sandbox Code Playgroud)

我的测试方法

方法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();
}
Run Code Online (Sandbox Code Playgroud)

方法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();
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 8

您创建了一个Mock<IResponseMessage>,MockBehavior.Strict默认使用哪个

MockBehavior.Strict:使mock始终为没有相应设置的调用抛出异常.

在代码中的某处,您正在调用未配置设置的成员.我建议为您打算在测试期间调用的所有成员创建一个设置

对于方法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
Run Code Online (Sandbox Code Playgroud)

  • 虽然这似乎是真的,但为什么只有一些模拟似乎关心这个设置?我没有使用安装程序来设置我的大部分方法,但是,一个特别的模拟确实在一个极端情况下关心这一点。 (3认同)