FakeItEasy Setup对象未在测试方法中返回

时间:2014-12-23 14:01:42

标签: c# unit-testing mocking tdd fakeiteasy

我正在使用 FakeItEasy 假对象测试方法。假对象是 MemoryStream

[TestFixture]
public class ServerClientTests
{
    private IWebClient webClient;
    private ServerClient serverClient;

    [SetUp]
    public void Setup()
    {
        webClient = A.Fake<IWebClient>();
        serverClient = new ServerClient(webClient);

        var responseStreamBytes = Encoding.Default.GetBytes("OK");
        var responseStream = new MemoryStream();
        responseStream.Write(responseStreamBytes, 0, responseStreamBytes.Length);
        responseStream.Seek(0, SeekOrigin.Begin);

        var response = A.Fake<WebResponse>();
        A.CallTo(() => response.GetResponseStream()).Returns(responseStream);

        var request = A.Fake<WebRequest>();
        A.CallTo(() => request.GetResponse()).Returns(response);

        A.CallTo(() => webClient.GetRequest("http://localhost:8080/myserver")).Returns(request);

    }

        [Test]
        public void Test1()
        {
            var result = serverClient.GetRequest("http://localhost/myserver");

            Assert.AreEqual(2, result.Length);
      }
  }

这是测试下的代码:

public interface IWebClient
{
    WebRequest GetRequest(string url);
}

public class ServerClient
{
    private readonly IWebClient client;

    public ServerClient(IWebClient client)
    {
        this.client = client;
    }

    public Stream GetRequest(string url)
    {
        return client.GetRequest(url).GetResponse().GetResponseStream();
    }
}

当我运行测试时,它会给出测试异常=&gt; 预期:2但是:0

我在设置方法和调试测试中设置了断点。我看到Fake请求GetResponse()方法返回带有流的响应。 长度为2。

但在测试方法中,流长度为0。

有关于FakeItEasy的任何设置吗?或者我哪里错了?

1 个答案:

答案 0 :(得分:3)

您正在设置

 A.CallTo(() => webClient.GetRequest("http://localhost:8080/myserver"))
                         .Returns(request);

但随后致电

serverClient.GetRequest("http://localhost/myserver");

因此,webClient.GetRequest已通过"http://localhost/myserver",与期望值"http://localhost8080/myserver"不匹配,因此webClient会返回假MemoryStream它自己设计,默认行为。

您可能希望使两个网址相同。或者,如果您希望假冒webClient不仅仅响应一个网址,您就可以使用更复杂的argument matchers

将来,如果出现这种混淆,为什么配置的方法没有按照您想要的方式运行,您可以考虑暂时使用MustHaveHappened调用来检查FakeItEasy是否认为该方法是调用。我们认为FakeItEasy的错误信息非常适合在这种情况下提供帮助。

在您的情况下,如果您添加了类似

的测试
[Test]
public void Test2()
{
    var result = serverClient.GetRequest("http://localhost/myserver");

    A.CallTo(() => webClient.GetRequest("http://localhost:8080/myserver"))
        .MustHaveHappened();
}

它会说

Assertion failed for the following call:
  FakeItEasyQuestions.IWebClient.GetRequest("http://localhost:8080/myserver")
Expected to find it at least once but found it #0 times among the calls:
  1: FakeItEasyQuestions.IWebClient.GetRequest(url: "http://localhost/myserver")