Deniz
Deniz

Reputation: 21

How can I test methods containing Application.Current.Properties.ContainsKey("token")

I am trying to test the login for my Xamarin App, but in order for the App to work, I have to create a token. The method for that looks like this:

public string RetrieveToken()
{
    if (Application.Current.Properties.ContainsKey("token"))
    {
         return Application.Current.Properties["token"] as string;
    }
    return null;
}

But as the test runs through I receive a NullReferenceError, because Application.Current.Properties.ContainsKey("token") can't be used within a test. So my question is if there is a way to evade that.

Upvotes: 2

Views: 1259

Answers (1)

Iain Smith
Iain Smith

Reputation: 9703

Are you using any dependency injection in this project? I did something similar using Application.Current.Resources as we were writing unit tests for the ViewModel.

You could register the Application.Current.Properties as a property on a service. Then use the service for your project and mock the property in your tests.

For Example, if you are using Microsoft Unity DI you could do something like this:

public interface IAppPropertyService
{
    IDictionary<string, object> Properties { get; set; }
}

public class AppPropertyService : IAppPropertyService
{
    public const string AppPropertiesName = "AppProperties";

    public IDictionary<string, object> Properties { get; set; }

    public AppPropertyService([IocDepndancy(AppPropertiesName)] IDictionary<string, object> appProperties)
    {
        Properties = appProperties;
    }
}

then register service like this in your App:

Container.RegisterInstance<IDictionary<string, object>>(AppPropertyService.AppPropertiesName, Application.Current.Properties);
Container.RegisterType<IAppPropertyService, AppPropertyService>();

and like this in your tests with a mocked version of Application.Current.Properties, e.g. just a Dictionary:

Container.RegisterInstance<IDictionary<string, object>>(AppPropertyService.AppPropertiesName, new Dictionary<string, object>());
Container.RegisterType<IAppPropertyService, AppPropertyService>();

Just be sure to use the PropertyService in your project rather than Application.Current.Properties something like this:

public string RetrieveToken()
{
    var propertyService = Container.Resolve<IAppPropertyService>();

    if (propertyService.Properties.ContainsKey("token"))
    {
         return propertyService.Properties["token"] as string;
    }
    return null;
}

Upvotes: 2

Related Questions