MessagingCenter回调未能注册

时间:2019-10-02 22:35:36

标签: c# xamarin xamarin.forms

我正在使用xamarin.forms制作应用程序,但是单元测试部分存在问题。问题是,当测试用例单独运行时,它通过了,但是当我运行所有测试时,它失败了。

using EmpresaPersonal.Modelos;
using EmpresaPersonal.ModelosVisuales;
using EmpresaPersonal.Services;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xunit;

namespace EmpresaPersonal.Test
{
    public class PruebasVMEditarContacto
    {
        [Fact]
        public async Task GuardarContactoSeteaCorrectamenteAsync()
        {
            // Preparamos el editor y los eventos
            var store = new MockDataStore();
            var mockNavegacion = ServiciosFalsos.MockIrAtras();
            var editor = new MVEditarContacto(store, mockNavegacion.Object)
            {
            // Initializer setters...
            };

            bool llamado = false;
            MessagingCenter.Subscribe<MVEditarContacto, string>(this, MVEditarContacto.EventoContactoCreado, async (s, idContacto) => // This line throws a NullReferenceException
            {
                var contacto = await store.GetItemAsync(idContacto);
                // Algunos chequeos van por acá
                Assert.NotNull(contacto);
                Assert.Equal(editor.Nombre.Valor, contacto.Nombre);
                Assert.Equal(editor.Empresa.Valor, contacto.Empresa);
                Assert.Equal(editor.TelefonoPrincipal.Valor, contacto.TelefonoPrincipal);
                Assert.Equal(editor.TelefonoSecundario.Valor, contacto.TelefonoSecundario);
                llamado = true;
            });
            editor.GuardarContacto.Execute(null);
            await editor.EsperarCompletarAsync();
            Assert.True(llamado, "El evento no fue llamado.");
            mockNavegacion.Verify(m => m.AtrasAsync());
        }
    }
}

除了在此块中实例化的模型中的MessagingCenter.Send外,我什么都没用。我必须说,我对模型的另一个测试是该模型的订阅者,该模型与构造函数中的同一事件(该模型是订阅者)相同。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,回答自己:

我看到,当对Xamarin.forms相关的代码(例如MessagingCenter)进行单元测试时,最好的方法是从Xunit.Runner.Devices测试运行程序(具有真实且已初始化的xamarin.forms环境的ACA)运行测试。

我发现的最好的例子是EShop on containers移动应用。

我刚刚离开我的项目,并在很大程度上基于Prism.Forms创建了一个新项目,因为它是在IOC容器之上构建的,因此可以简化对此类事情的单元测试。

谢谢

相关问题