Joel Dean
Joel Dean

Reputation: 2454

How to test an async method in Windows Phone

I need to write an unit test in Windows Phone to test if my data is being deserialized to the correct type. This is what I have done so far.

[TestMethod]
    [Asynchronous]
    public void SimpleTest()
    {
        await pots = help.potholes();

I am getting an error saying that "pots" is not awaitable. Pots is a list that should accept the result from the potholes function that is making an asynchronous call to my webservice.

This is the method making the call using Restsharp.

public void GetAllPotholes(Action<IRestResponse<List<Pothole>>> callback)
    {

        var request = new RestRequest(Configuration.GET_POTHOLE_ALL,Method.GET);
        request.AddHeader("Accept", "application/json");
        _client.ExecuteAsync(request, callback);

    }

How can I make pots awaitable? Whats the correct way to test rest services in Windows Phone?

I am using the Windows Phone Toolkit Test Framework

This is the tutorial I am following. Asynchronous tests

Upvotes: 0

Views: 590

Answers (3)

Juan Mejia
Juan Mejia

Reputation: 9

as matt expresses the term Asynchronous is now being used in multiple contexts, in the case of test methods on Windows Phone, as you can see in your code piece is not a keyword, but an attributed that has the goal of releasing the working thread to allow other processes to run and for your test method to wait for any changes that could happen in the UI or from a service request.

You can do something like this to make your test to wait.

[TestClass]
public class ModuleTests : WorkItemTest
{
    [TestMethod, Asynchronous]
    public void SimpleTest()
    {
        var pots;
        EnqueueDelay(TimeSpan.FromSeconds(.2)); // To pause the test execution for a moment.
        EnqueueCallback(() => pots = help.potholes());
        // Enqueue other functionality and your Assert logic
        EnqueueTestComplete();
    }
}

Upvotes: 1

Matt Lacey
Matt Lacey

Reputation: 65564

The term "asynchronous" is overloaded in .net now.

The article you are referencing refers to awaitable methods, not methods that are asynchronous via callbacks.

Here's a rough idea of how you could test this.

[TestMethod]        
[Asynchronous]
public void SimpleTest()
{
    // set up your system under test as appropriate - this is just a guess
    var help = new HelpObject();

    help.GetAllPotholes(
        response =>
        {
            // Do your asserts here. e.g.
            Assert.IsTrue(response.Count == 1);

            // Finally call this to tell the test framework that the test is now complete
            EnqueueTestComplete();
        });
}

Upvotes: 1

nkchandra
nkchandra

Reputation: 5557

You are using the async .. await in the wrong way

Try this

public async void SimpleTest()
{
    pots = await help.potholes();
    ....
}

Upvotes: 0

Related Questions