jeudi 29 octobre 2020

C# unit testing csv

I need to test quantity of headers in csv. Below is my approach to solve this problem. I created two methods first counts quantity of headers in csv file and the second counts number of commas in first row of file. If they are equal test is positive, if not negative. I use shouldly and it works fine, but I need to find different approach to this matter using fixie. Below is code:

using System;
using System.Collections.Generic;
using System.Text;
using LumenWorks.Framework.IO.Csv;
using System.IO;
using System.Linq;

namespace Test
{
    public class CsvParser
    {
        public int CountCsvHeaders()
        {
            using (var reader = new System.IO.StreamReader(@"csv file", Encoding.Default))
            {
                Char quotingCharacter = '\0'; // no quoting-character;
                Char escapeCharacter = quotingCharacter;
                Char delimiter = ',';
                int count = 0;
                using (var csv = new CsvReader(reader, true, delimiter, quotingCharacter, escapeCharacter, '\0', ValueTrimmingOptions.All))
                {
                    
                    string[] headers = csv.GetFieldHeaders();

                    foreach (string head in headers)
                    {
                        count = count + 1;
                    }
                }
                return count;
            }
        }
        public int Count()
        {
            string line = File.ReadLines(@"csv file").First();
            int count = line.Split(',').Length;
            return count;
        }
       
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using Shouldly;
using Fixie;
using NFluent;


namespace Test
{
    [TestClass]
    public class SimpleTests
    {
        
        [Test]
        public void should_csv_columns_quantity()
        {
            var parser = new CsvParser();
            int ColumnsQuantity = parser.CountCsvHeaders();
            int Count = parser.Count();
            ColumnsQuantity.ShouldBe(Count);
        }
       
        
    }
}

Aucun commentaire:

Enregistrer un commentaire