lundi 22 juin 2020

Proper Way to Test a file method with .net

I'm new to .net and testing. My following code looks like this:

using System.Xml.Linq;
    public class AnimalXmlService
    {
        public Animal GetAnimalInfoFromXml(string url) {
            XElement xml_doc = GetXmlInfo(url);
            if (xml_doc == null)
            {
                return null;
            } else { 
                XElement animal_info = xml_doc.Element("Animal");
                string animal_name = GetAnimalName(animal_info);
                int animal_id = GetAnimalId(animal_info);

                return new Animal(animal_id, animal_name);
            }
        }

        private XElement GetXmlInfo(string url)
        {
            try
            {
                XElement animal_xml_info = XElement.Load(url);
                return animal_xml_info;
            }
            catch
            {
                return null;
            }
        }


        private int GetAnimalName(XElement animal_info)
        {
           ....
        }

} 

My question is how do I stub the GetAnimalInfoFromXml to return a file? I have the sample xml file that I will be using instead of making a request. Here's my following test. I'm also wondering if there are better ways to refactor this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace AnimalXmlService
{
    [TestFixture]
    public class AnimalXmlTest
    {

        [Test]
        public void extracts_valid_name()
        {
           //get xml file?

            animalService AnimalXmlService = new AnimalXmlService();
            name = animalService.GetAnimalName(xml_file);
            Assert.AreEqual(name, "bobby the tiger");
        }

        [Test]
        public void extracts_valid_id()
        {
           //get xml file?
           xml_file = fetch_file //is this appropriate?

            animalService AnimalXmlService = new AnimalXmlService();
            id = animalService.GetAnimalId(xml_file);
            Assert.AreEqual(name, "2");
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire