How to write a unittest with Device.OnPlatform()

FokkeVermeulenOldFokkeVermeulenOld ✭✭USMember ✭✭

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

Answers

  • 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

  • FokkeVermeulenOldFokkeVermeulenOld ✭✭ USMember ✭✭

    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 Xamurai USXamarin Team Xamurai

    @MikeScott8 I don't even think my fork is necessary any more - I just checked the original repo https://github.com/nunit/nunit.xamarin 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

  • PavloVorontsovPavloVorontsov USMember

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

  • JFMGJFMG ✭✭ DEMember ✭✭
    edited April 12

    The more modern way is to use Xamarin Essentials Device Information.
    See https://docs.microsoft.com/en-us/xamarin/essentials/device-information

    if (DeviceInfo.Platform == DevicePlatform.Android)
        // Attention: This is code that the unit tests won't recognize
    
Sign In or Register to comment.