Xamarin Unit Test - Xamarin.Essentials.NotImplementedInReferenceAssemblyException using Xamarin.Essentials.Connectivity

Buddhima Kudagama 1 Reputation point
2021-07-09T10:27:37.257+00:00

I was creating a unit test for one of my view models using xunit.

and the test fails when create an object of my ViewModel and I'm having the following error

"Xamarin.Essentials.NotImplementedInReferenceAssemblyException : This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."

And here is the Stack trace

at Xamarin.Essentials.Connectivity.get_PlatformNetworkAccess()
at Xamarin.Essentials.Connectivity.get_NetworkAccess()
at MyPCLProject.ViewModels.Base.BaseViewModel..ctor(INavigationService pNavigationService, IErrorHandlingService pErrorHandlingService) in /Volumes/Workspace/MyDirectory/XamarinTemplate/MyPCLProject/MyPCLProject/MyPCLProject/ViewModels/Base/BaseViewModel.cs:line 67
at MyPCLProject.ViewModels.BookDetailViewModel..ctor(INavigationService pNavigationService, IErrorHandlingService pErrorHandlingService) in /Volumes/Workspace/MyDirectory/XamarinTemplate/MyPCLProject/MyPCLProject/MyPCLProject/ViewModels/BookDetailViewModel.cs:line 18
at MyPCLProject.UnTestCore.UnitTest1.BookDetailViewModel_Initialize_Title_ShouldNotBe_Empty() in /Volumes/Workspace/MyDirectory/XamarinTemplate/MyPCLProject/MyPCLProject/MyPCLProject.UnTestCore/UnitTest1.cs:line 43

The reason for the error is I have a Connectivity property in my view model

private bool _isConnectionAvailable =
            Connectivity.NetworkAccess == NetworkAccess.Internet
            || Connectivity.NetworkAccess == NetworkAccess.ConstrainedInternet;

When I comment above property, the test runs fine.

Here is my test method

[Fact]
        public void BookDetailViewModel_Initialize_Title_ShouldNotBe_Empty()
        {
            using (var mock = AutoMock.GetLoose())
            {
                Book book = new Book()
                {
                    Author = "TestAuthor",
                    Id = "1",
                    Title = "TestTitle"
                };

                // arrange
                BookDetailViewModel vm = new BookDetailViewModel(_navigationService.Object,_errorHandlingService.Object);
                //vm.InitializeWith(book);

                //Assert.NotEmpty(vm.Title);
                //Assert.Equal("TestTitle", vm.Title);

            }

        }

How can I solve this issue?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,355 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.