单元测试 Xamarin.Forms 应用程序时抛出 Xamarin.Essentials.NotImplementedInReferenceAssemblyException

Sah*_*nna 5 c# nunit unit-testing xamarin.forms xamarin.essentials

我正在为我的 Xamarin.Forms 应用程序运行单元测试,并且单元测试抛出Xamarin.Essentials.NotImplementedInReferenceAssemblyException

在此处输入图片说明

我为应用程序创建了一个单元测试项目(使用 NUnit 3.12.0)并编写了以下代码来测试功能。

[TestFixture()]
public class Test
{
    [Test()]
    public void TestCase()
    {
        AutoResetEvent autoEvent = new AutoResetEvent(true);

        SomeClass someClass = new SomeClass();
        someClass.SomeFunction((response) =>
        {
            Assert.AreEqual(response, "Hello")
            autoEvent.Set();
        });

        autoEvent.WaitOne(); //** Xamarin.Essentials.NotImplementedInReferenceAssemblyException thrown here**
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是来自 Xamarin.Forms 应用程序的测试代码:

public class SomeClass
{
    
    public void SomeFunction(Action<string> callback)
    {
        // asynchronous code...
        callback("Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

上述功能在 Xamarin.Forms 应用中运行良好。

注意:我读到可以使用 await/async,但是,我必须对整个项目进行更改。目前这不是一个可行的解决方案。


编辑 1: 我创建了一个示例 Xamarin.Forms 项目,其中包含单元测试。该项目可在此处获得

Nko*_*osi 1

虽然您已经声明此时无法将主题函数设为异步,但是可以将测试设为异步。

TaskCompletionSource可用于等待调用回调。

[TestFixture()]
public class Test {
    [Test()]
    public async Task TestCase() {
        //Arrange
        TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
        Action<string> callback = (arg) => {
            tcs.TrySetResult(arg);
        };
        SomeClass someClass = new SomeClass();

        //Act
        someClass.SomeFunction(callback);            
        string response = await tcs.Task;

        //Assert
        Assert.AreEqual(response, "Hello")
    }
}
Run Code Online (Sandbox Code Playgroud)