Search code examples
c#flurl

Flurl Testing: How to setup response based on conditions?


I have a method that makes two HTTP calls to two different urls using Flurl. I need to unit test this method in which I want Flurl to respond with two different responses. How can I set this up?

My test class is like:

public class SUT
{
    public async Task Mut(object obj)
    {
        var x = await url1.PostJsonAsync(obj).ReceiveJson();

        if ((bool)x.property = true)
        {
            var y = await url2.GetJsonAsync();
            // Process y.
        }
    }
}

I have a test class as below:

public class TestSut : Disposable
{
    private readonly HttpTest httpTest;

    public TestSut()
    {
        httpTest = new HttpTest();
    }

    [Fact]
    public async Task TestMut()
    {
        // call Mut...
    }

    public void Dispose()
    {
       httpTest?.Dispose();
    }
}

What I would like is something along the lines of:

httpTest.ForUrl(url1).ResponsdWithJson(...);
httpTest.ForUrl(url2).ResponsdWithJson(...);

Solution

  • The short answer is no, you can't configure different behavior by URL today, but it's coming in 3.0. I'll update this when it's released (or hopefully someone else will if I forget :).

    In this particular case though, assuming your SUT code at least somewhat resembles the real code you're targeting, it looks like url1 will always be called before url2, so if you just queue the responses in the same order, Flurl will guarantee that they are returned in the same order.

    httpTest
        .ResponsdWithJson(/* fake response for url1 */)
        .ResponsdWithJson(/* fake response for url2 */);
    

    Of course the SUT may not actually call things in a determinate order like that, in which case you'll have to wait for 3.0 unfortunately.