当 运行 在一起时,Mvvmcross 测试不同的视图模型失败

Mvvmcross Testing different view models fails when running together

我遇到了一个有趣的错误。我的 xamarin 移动应用程序有两个测试文件,都在测试视图模型:

public class TestFirstViewModel : MvxIoCSupportingTest 
{

    public void AdditionalSetup() {
    //Register services and dependencies here.
    }

    [Fact]
    public TestMethod1() {
    // Successful test code here.
    }
}

在一个文件中。在另一个文件中,我有:

public class TestSecondViewModel : MvxIoCSupportingTest 
{

    public void AdditionalSetup() {
    //Register services and dependencies here, slightly different from first
    }

    [Fact]
    public TestMethod2() {
    // Successful test code here.
    }
}

当我单独 运行 这些文件时(我使用的是 xunit),它们工作得很好。但是,当我 运行 它们在一起时,我在其中一个测试用例中收到以下错误:

Result Message: Cirrious.CrossCore.Exceptions.MvxException : You cannot create more than one instance of MvxSingleton
Result StackTrace:  
at Cirrious.CrossCore.Core.MvxSingleton`1..ctor()
   at Cirrious.CrossCore.IoC.MvxSimpleIoCContainer..ctor(IMvxIocOptions options)
   at Cirrious.CrossCore.IoC.MvxSimpleIoCContainer.Initialize(IMvxIocOptions options)
   at Cirrious.MvvmCross.Test.Core.MvxIoCSupportingTest.ClearAll()
   at Cirrious.MvvmCross.Test.Core.MvxIoCSupportingTest.Setup()
   at Project.Test.TestFirstViewModel.TestMethod1() in ...

谁能告诉我这是怎么回事?

我最终通过更改测试框架解决了这个问题。我有不同的 ioc 单例初始化,因为,嗯,它们是不同的测试用例,需要不同的 inputs/mocks。我没有使用 Xunit,而是求助于 Nunit,他们的缓存清除更加明确:Xunit 并不完全相信设置和拆卸,因此它使这样的测试环境更加困难。

我在构造函数中设置了一些东西并添加了这个检查:

    public PaymentRepositoryTests()
    {
        if (MvxSingletonCache.Instance == null)
        {
            Setup();
        }

        //other registerings.
    }`

我还实现了 IDisposable 接口

public void Dispose()
    {
        ClearAll();
    }

但不知道这有多大影响..

问题源于 XUnit 的并行化,没有选择进行适当的拆卸。您可以通过添加以下内容在测试项目的 AssemblyIndo.cs 文件中禁用并行化:

[assembly: CollectionBehavior(DisableTestParallelization = true)]

它与 xunit 一起工作正常
在您的 xunit PCL 项目中复制 MvxIocSupportingTest 和 Mvxtest。 修改 MvxTest 以删除属性并使用简单的构造函数:

public class MvxTest : MvxIoCSupportingTest
{
    protected MockMvxViewDispatcher MockDispatcher { get; private set; }

    public MvxTest()
    {
        Setup();
    }
    ...

并且在你们每个测试中,派生自 IClassFixture

public class TestRadiosApi : IClassFixture<MvxTest>
{
    [Fact]
    public async Task TestToken()
    {
    ...

xunit 将为所有测试只创建一次 MvxTest class。

我使用集合属性解决了这个问题。

[Collection("ViewModels")]
class ViewModelATest : BaseViewModelTest {
...
}

[Collection("ViewModels")]
class ViewModelBTest : BaseViewModelTest {
...
}

基本视图模型测试 class 具有模拟调度程序并在附加设置方法中执行单例注册。

我的每个测试都在开头调用 ClearAll()