Moq.Mock 异常调用失败,模拟行为严格

Moq.Mock Exception with invocation failed with mock behavior strict

我是 Moq 框架的新手,我已经编写了一个测试方法,但出现以下错误。我找不到我遗漏的地方。

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


An exception of type 'Moq.MockException' occurred in Moq.dll but was not handled in user code

Additional information: IResponseMessage.ReadContentAsString() invocation failed with mock behavior Strict.

All invocations on the mock must have a corresponding setup.

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


}

我的测试方法

方法一

[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();
}

方法二

[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();
}

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

MockBehavior.Strict : Causes the mock to always throw an exception for invocations that don't have a corresponding setup.

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

对于方法 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