我正在用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`之外,我没有使用其他任何东西。我不得不说,我对订阅此模型的模型进行了另一个测试,该模型的构造函数(该模型是订阅者)中的相同事件。
有什么想法吗?
发布于 2019-10-13 23:14:49
我发现,当单元测试像MessagingCenter这样与xamarin.forms相关的代码时,最好的方法是从Xunit.Runner.Devices测试运行器(A.C.A.,具有真实的、初始化的xamarin.forms环境)运行测试。
我找到的最好的例子是EShop on containers移动应用程序。
我刚刚离开我的项目,开始了一个主要基于Prism.Forms的新项目,以简化这类事情的单元测试,因为它是在IOC容器之上构建的。
https://stackoverflow.com/questions/58210179
复制相似问题