Objetivo
Crear un objeto mock, usando Moq and XUnit, para cargar la sección "Character/Skills" y así aumentar la cobertura de las pruebas unitarias.
The SUT (en algún punto), lee y carga las configuraciones de la siguiente manera:
var skills = Configuration.GetSection(“Character:Skills”);
Del siguiente appSetting:
{
"dummyConfig1": {
"Description": "bla bla bla...",
},
"Character": {
"Name": "John Wick",
"Description": "A retired hitman seeking vengeance for the killing of the dog given to him...",
"Skills": [
{
"Key": "CQC Combat",
"Id": "15465"
},
{
"Key": "Firearms",
"Id": "14321"
},
{
"Key": "Stealth",
"Id": "09674"
},
{
"Key": "Speed",
"Id": "10203"
}
],
"DummyConf2": "more bla bla bla..."
}
Lectura previa
Leyendo estos post (y otros en inglés, como resultado de una búsqueda en Google), noté que para la preparación de los "mocks", usan únicamente tipos de datos "string" o en su defecto, un objeto new Mock<IConfigurationSection> (sin configuraciones):
- Stack Overflow - how to mock Configuration.GetSection(“foo:bar”),
- Mocking IConfiguration extension method
- Mocking IConfiguration Getvalue() extension method in Unit Test
Restricción: Copiando el archivo "appSetting" dentro del proyecto de Testing (o creando un MemoryStream) para cargar las configuraciones reales podría resolver este escenario, pero ahí sería una prueba "de integración", en vez de "unitarias"; ya que habría dependencias de operaciones de E/S.
Abordaje
La ideal del código (más adelante) está "mocando" cada una de las propiedades (key/id) para después armar un árbol parecido a este:
- "Character" ------ Configuración a ser leída, usando
GetSection()
y luegoGet<T>()
- "Skills" ------ Lista de configuración con los atributos
- "Key" - "CQC Combat" ------ Valores primitivos 1
- "Id" - "15465" ------ Valores primitivos 2
- "Skills" ------ Lista de configuración con los atributos
El código
var skillsConfiguration = new List<SkillsConfig>
{
new SkillsConfig { Key = "CQC Combat" , Id = "15465" },
new SkillsConfig { Key = "Firearms" , Id = "14321" },
new SkillsConfig { Key = "Stealh" , Id = "09674" },
new SkillsConfig { Key = "Speed" , Id = "10203" },
};
var configurationMock = new Mock<IConfiguration>();
var mockConfSections = new List<IConfigurationSection>();
foreach (var skill in skillsConfiguration)
{
var index = skillsConfiguration.IndexOf(skill);
//Set the Key string value
var mockConfSectionKey = new Mock<IConfigurationSection>();
mockConfSectionKey.Setup(s => s.Path).Returns($"Character:Skills:{index}:Key");
mockConfSectionKey.Setup(s => s.Key).Returns("Key");
mockConfSectionKey.Setup(s => s.Value).Returns(skill.Key);
//Set the Id string value
var mockConfSectionId = new Mock<IConfigurationSection>();
mockConfSectionId.Setup(s => s.Path).Returns($"Character:Skills:{index}:Id");
mockConfSectionId.Setup(s => s.Key).Returns("Id");
mockConfSectionId.Setup(s => s.Value).Returns(skill.Id);
//Merge the attribute "key/id" as Configuration section list
var mockConfSection = new Mock<IConfigurationSection>();
mockConfSection.Setup(s => s.Path).Returns($"Character:Skills:{index}");
mockConfSection.Setup(s => s.Key).Returns(index.ToString());
mockConfSection.Setup(s => s.GetChildren()).Returns(new List<IConfigurationSection> { mockConfSectionKey.Object, mockConfSectionId.Object });
//Add the skill object with merged attributes
mockConfSections.Add(mockConfSection.Object);
}
// Add the Skill's list
var skillsMockSections = new Mock<IConfigurationSection>();
skillsMockSections.Setup(cfg => cfg.Path).Returns("Character:Skills");
skillsMockSections.Setup(cfg => cfg.Key).Returns("Skills");
skillsMockSections.Setup(cfg => cfg.GetChildren()).Returns(mockConfSections);
//Mock the whole section, for using GetSection() method withing SUT
configurationMock.Setup(cfg => cfg.GetSection("Character:Skills")).Returns(skillsMockSections.Object);
Resultados esperados
Ejecutando el sistema original, obtengo la lista instanciada con sus respectivos valores. Aquí la imagen:
Resultados mocados
El código arriba, obtengo la lista instanciada pero los valores de los atributos vienen nulos. Aquí la imagen: