Forum Xamarin Xamarin.Forms

How to write a unittest with Device.OnPlatform()

Hello I want to test a method on the pcl-part. The IOS-Part do other stuff than the android one.

For example the ios-part make a ModalPush and the android-part a normal one

How do you test such parts?

Best Answer


  • stvansolanostvansolano UMInsider, University ✭✭✭
    edited October 2015

    Hello @FokkeVermeulen have you tried abstracting the ModalPush action (interface preferly) and then mock it out? Moq is good one I generally use

  • Thanks for the answers, will test it

  • stvansolanostvansolano UMInsider, University ✭✭✭

    @FokkeVermeulen if you focusing more to be UI testing you can also consider Xamarin Test Cloud so you could even run and see your code in real devices. Here is a link:

    Getting Started with Xamarin TestCloud

    Please come back later and let us know which choices worked better for you :)

  • ArminTelkerArminTelker USMember
      var field = typeof(Device).GetRuntimeProperty("OS");
      field.SetValue(null, TargetPlatform.Android);
  • MikeScott8MikeScott8 USUniversity

    @CraigDunn Can you point to a post or something on how to use the forked Nunit to do unit tests on a device?

  • CraigDunnCraigDunn USXamarin Team Xamurai

    @MikeScott8 I don't even think my fork is necessary any more - I just checked the original repo and it looks like they have more recent Xamarin.Forms support.

    There are instructions to set it up in the readme. Set the platform project (eg the iOS NUnit runner) as the startup project, and make sure you've referenced the assemblies needed to run the tests.

  • MikeScott8MikeScott8 USUniversity

    OK thanks

  • There is another workaround.
    You can use Prism.Services.RuntimePlatform instead of Device.RuntimePlatform and than simply moq IDeviceService.

  • JFMGJFMG DEMember ✭✭
    edited April 2019

    The more modern way is to use Xamarin Essentials Device Information.

    if (DeviceInfo.Platform == DevicePlatform.Android)
        // Attention: This is code that the unit tests won't recognize
  • ramonesteban78ramonesteban78 ESUniversity ✭✭

    You can use the following nuget package in your Unit Test projects:

Sign In or Register to comment.