Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 嘲笑流媒体阅读器_C#_Unit Testing_C# 4.0_Nunit_Moq - Fatal编程技术网

C# 嘲笑流媒体阅读器

C# 嘲笑流媒体阅读器,c#,unit-testing,c#-4.0,nunit,moq,C#,Unit Testing,C# 4.0,Nunit,Moq,我有一个使用StreamReader的方法,我想对它进行单元测试。我将StreamReader的创建拆分为一个单独的类,并试图模拟该类,但我的单元测试仍然给我错误 用于抽象StreamReader的类/接口 public interface IPathReader { TextReader CreateReader(string path); } public class PathReader : IPathReader { public TextReader CreateRe

我有一个使用StreamReader的方法,我想对它进行单元测试。我将StreamReader的创建拆分为一个单独的类,并试图模拟该类,但我的单元测试仍然给我错误

用于抽象StreamReader的类/接口

public interface IPathReader
{
    TextReader CreateReader(string path);
}

public class PathReader : IPathReader
{
    public TextReader CreateReader(string filePath)
    {
        return new StreamReader(filePath);
    }
}
类,该类包含GetLastRowInFile(我正在尝试进行单元测试的方法)

编辑2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Data;
using System.Globalization;
using System.Collections;
using System.Reflection;
using System.ComponentModel;

namespace FrazerMann.CsvImporter.Entity
{
    public interface IPathReader
    {
        TextReader CreateReader(string path);
    }

    public class PathReader : IPathReader
    {
        public TextReader CreateReader(string filePath)
        {
            return new StreamReader(filePath);
        }
    }


public interface IIOManager
{
    Stream OpenFile(string path);

    int GetLastRowInFile(string filePath, List<String> errorMessageList);

    int GetNumberOfColumnsInFile(string filePath, List<string> errorMessageList);

    bool IsReadOnly(string filePath);
}


public class IOManager : IIOManager
{
    private IPathReader _reader;

    public IOManager(IPathReader reader)
    {
        this._reader = reader;
    }


    public Stream OpenFile(string path)
    {
        return new FileStream(path, FileMode.Open);
    }


    public int GetNumberOfColumnsInFile(string filePath, List<String> errorMessageList)
    {
        int numberOfColumns = 0;
        string lineElements;

        try
        {
            using (StreamReader columnReader = (StreamReader)_reader.CreateReader(filePath))
            {
                lineElements = columnReader.ReadLine();
                string[] columns = lineElements.Split(',');
                numberOfColumns = columns.Length;
            }
        }
        catch (Exception ex)
        {
            errorMessageList.Add(ex.Message);
            numberOfColumns = -1;
        }
        return numberOfColumns;
    }


    public int GetLastRowInFile(string filePath, List<String> errorMessage)
    {
        int numberOfRows = 0;
        string dataRow;

        try
        {
            using (StreamReader rowReader = (StreamReader)_reader.CreateReader(filePath))
            {
                while ((rowReader.Peek()) > -1)
                {
                    dataRow = rowReader.ReadLine();
                    numberOfRows++;
                }
                return numberOfRows;
            }
        }
        catch (Exception ex)
        {
            errorMessage.Add(ex.Message);
            return -1;
        }
    }


    public bool IsReadOnly(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.IsReadOnly;
    }
}


public interface IVerificationManager
{
    void ValidateCorrectExtension(string filePath, List<String> errorMessageList);

    void ValidateAccessToFile(string filePath, List<String> errorMessageList);

    void ValidateNumberOfColumns(string filePath, int dataTypeCount, List<String> errorMessageList);

    int ValidateFinalRow(int finalRow, string filePath, List<String> errorMessageList);

    void ValidateRowInputOrder(int initialRow, int finalRow, List<String> errorMessageList);

    void EnumeratedDataTypes(UserInputEntity inputs, List<String> errorMessageList);

    int GetProgressBarIntervalsForDataVerification(int initialRow, int finalRow, List<String> errorMessageList);
}


public class VerificationManager : IVerificationManager
{
    private IIOManager _iomgr;

    public VerificationManager(IIOManager ioManager)
    {
        this._iomgr = ioManager;
    }

    public void ValidateCorrectExtension(string filePath, List<String> errorMessageList)
    {
        if (filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) | filePath.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) { }
        else
        {
            errorMessageList.Add("Selected file does not have a compatable extension.");
        }
    }

    public void ValidateAccessToFile(string filePath, List<String> errorMessageList)
    {
        try
        {

            if (_iomgr.IsReadOnly(filePath) == true) { }
            else
            {
                errorMessageList.Add("Can not read/write to the specified file.");
            }
        }
        catch (Exception e)
        {
            errorMessageList.Add(e.Message);
        }
    }

    public void ValidateNumberOfColumns(string filePath, int userSpecifiedColumnCount, List<String> errorMessageList)
    {
        int numberOfColumnsInFile = _iomgr.GetNumberOfColumnsInFile(filePath, errorMessageList);

        if (userSpecifiedColumnCount != numberOfColumnsInFile) errorMessageList.Add("Number of columns specified does not match number present in file.");
    }

//**TEST APPLIES HERE**

    public int ValidateFinalRow(int finalRow, string filePath, List<String> errorMessageList)
    {
        int totalNumberOfRowsInFile = 0;

        totalNumberOfRowsInFile = _iomgr.GetLastRowInFile(filePath, errorMessageList);

        if (totalNumberOfRowsInFile != -1)
        {
            if (finalRow == 0)
            {
                return totalNumberOfRowsInFile;
            }
            else
            {
                if (finalRow > totalNumberOfRowsInFile)
                {
                    errorMessageList.Add("Specified 'Final Row' value is greater than the total number of rows in the file.");
                }
            }
        }
        return 0;
    }

    public void ValidateRowInputOrder(int initialRow, int finalRow, List<String> errorMessageList)
    {
        if (initialRow > finalRow)
        {
            errorMessageList.Add("Initial row is greater than the final row.");
        }
    }

    public void EnumeratedDataTypes(UserInputEntity inputs, List<String> errorMessageList)
    {
        inputs.EnumeratedDataTypes = new int[inputs.DataTypes.Count];
        try
        {
            for (int i = 0; i < inputs.DataTypes.Count; i++)
            {
                inputs.EnumeratedDataTypes[i] = (int)Enum.Parse(typeof(Enumerations.ColumnDataTypes), inputs.DataTypes[i].ToUpper());
            }
        }
        catch (Exception ex)
        {
            errorMessageList.Add(ex.Message);
        }
    }

    public int GetProgressBarIntervalsForDataVerification(int initialRow, int finalRow, List<String> errorMessageList)
    {
        int progressBarUpdateInverval = -1;

        try
        {
            int dif = (finalRow - initialRow) + 1;
            progressBarUpdateInverval = dif / 100;

            if (progressBarUpdateInverval == 0)
            {
                progressBarUpdateInverval = 1;
            }
        }
        catch (Exception ex)
        {
            errorMessageList.Add(ex.Message);
        }
        return progressBarUpdateInverval;
    }
}



public class EntityVerification
{

    private VerificationManager _vmgr;

    public EntityVerification(VerificationManager vManager)
    {
        this._vmgr = vManager;
    }


    public void VerifyUserInputManager(UserInputEntity inputs, List<string> errorMessageList)
    {
        _vmgr.ValidateCorrectExtension(inputs.CsvFilePath ,errorMessageList);
        _vmgr.ValidateCorrectExtension(inputs.ErrorLogFilePath, errorMessageList);

        _vmgr.ValidateAccessToFile(inputs.CsvFilePath, errorMessageList);
        _vmgr.ValidateAccessToFile(inputs.ErrorLogFilePath, errorMessageList);

        _vmgr.ValidateNumberOfColumns(inputs.CsvFilePath, inputs.DataTypes.Count, errorMessageList);

        inputs.FinalRow = _vmgr.ValidateFinalRow(inputs.FinalRow, inputs.CsvFilePath, errorMessageList);

        _vmgr.ValidateRowInputOrder(inputs.InitialRow, inputs.FinalRow, errorMessageList);

        _vmgr.EnumeratedDataTypes(inputs, errorMessageList);

        inputs.ProgressBarUpdateIntervalForDataVerification = _vmgr.GetProgressBarIntervalsForDataVerification(inputs.InitialRow, inputs.FinalRow, errorMessageList);
    }
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
使用System.Windows.Forms;
使用系统数据;
利用制度全球化;
使用系统集合;
运用系统反思;
使用系统组件模型;
命名空间FrazerMann.CsvImporter.Entity
{
公共接口线程器
{
TextReader CreateReader(字符串路径);
}
公共类路径读取器:IPathReader
{
公共文本阅读器CreateReader(字符串文件路径)
{
返回新的StreamReader(文件路径);
}
}
公共接口管理器
{
流OpenFile(字符串路径);
int GetLastRowInFile(字符串文件路径,列表错误消息列表);
int GetNumberOfColumnsInFile(字符串文件路径,列表错误消息列表);
bool IsReadOnly(字符串文件路径);
}
公共类IOManager:IIOManager
{
私人IPathReader_阅读器;
公共IOManager(IPathReader读卡器)
{
这个。_reader=reader;
}
公共流OpenFile(字符串路径)
{
返回新的文件流(路径,FileMode.Open);
}
public int GetNumberOfColumnsInFile(字符串文件路径,列表错误消息列表)
{
int numberOfColumns=0;
字符串行元素;
尝试
{
正在使用(StreamReader columnReader=(StreamReader)\ u reader.CreateReader(文件路径))
{
lineElements=columnReader.ReadLine();
string[]columns=lineElements.Split(',');
numberOfColumns=columns.Length;
}
}
捕获(例外情况除外)
{
errorMessageList.Add(例如消息);
numberOfColumns=-1;
}
返回numberOfColumns;
}
public int GetLastRowInFile(字符串文件路径,列表错误消息)
{
int numberOfRows=0;
字符串数据行;
尝试
{
使用(StreamReader rowReader=(StreamReader)\ u reader.CreateReader(文件路径))
{
而((rowReader.Peek())>-1)
{
dataRow=rowReader.ReadLine();
numberOfRows++;
}
返回numberOfRows;
}
}
捕获(例外情况除外)
{
errorMessage.Add(例如消息);
返回-1;
}
}
public bool IsReadOnly(字符串文件路径)
{
FileInfo fi=新的FileInfo(filePath);
返回fi.IsReadOnly;
}
}
公共接口IVerificationManager
{
void ValidateCorrectExtension(字符串文件路径、列表错误消息列表);
void ValidateAccessToFile(字符串文件路径,列表错误消息列表);
void validateEnumberOfColumns(字符串文件路径、int数据类型计数、列表错误消息列表);
int ValidateFinalRow(int finalRow、字符串文件路径、列表错误消息列表);
void ValidateRowInputOrder(int initialRow、int finalRow、List errorMessageList);
void EnumeratedDataTypes(UserInputEntity输入,列表errorMessageList);
int GetProgressBarIntervalsForDataVerification(int initialRow、int finalRow、List errorMessageList);
}
公共类验证管理器:IVerificationManager
{
私人管理人(iomgr);
公共验证管理器(IIOManager ioManager)
{
这个。_iomgr=ioManager;
}
public void ValidateCorrectExtension(字符串文件路径,列表错误消息列表)
{
if(filePath.EndsWith(“.txt”,StringComparison.OrdinalIgnoreCase)| filePath.EndsWith(“.csv”,StringComparison.OrdinalIgnoreCase)){}
其他的
{
errorMessageList.Add(“所选文件没有可兼容的扩展名。”);
}
}
public void ValidateAccessToFile(字符串文件路径,列表错误消息列表)
{
尝试
{
如果(_iomgr.IsReadOnly(filePath)==true){
其他的
{
errorMessageList.Add(“无法读取/写入指定文件”);
}
}
捕获(例外e)
{
errorMessageList.Add(e.Message);
}
}
public void validateEnumberOfColumns(字符串文件路径,int userSpecifiedColumnCount,List errorMessageList)
{
int numberOfColumnsInFile=\u iomgr.GetNumberOfColumnsInFile(文件路径,errorMessageList);
如果(userSpecifiedColumnCount!=numberOfColumnsInFile)errorMessageList.Add(“指定的列数与文件中的数字不匹配”);
}
//**测试适用于这里**
public int ValidateFinalRow(int finalRow、字符串文件路径、列表errorMessageList)
{
int totalNumberOfRowsInFile=0;
totalNumberOfRowsInFile=\u iomgr.GetLastRowInFile(文件路径,errorMessageList);
如果(totalNumberOfRowsInFile!=-1)
{
如果(finalRow==0)
{
返回totalNumberOfRowsInFile;
}
其他的
{
如果(finalRow>totalNumberOfRowsInFile)
{
errorMessageList.Add(“指定的“最终行”值大于文件中的行总数。”);
}
}
}
返回0;
}
public void ValidateRowInputOrder(int initialRow、int finalRow、List errorMessageList)
{
如果(初始行>最终行)
{
errorMessageList.Add(“初始行大于最后一行”);
}
}
public void EnumeratedDataTypes(UserInputEntity输入,列表errorMessageList)
{
inputs.EnumeratedDataTypes=newint[inputs.DataTypes.Count];
尝试
{
对于(int i=0;i    [Test]
    public void GetLastRowInFile_ReturnsNumberOfRows_Returns3()
    {
        string testString = "first Row" + Environment.NewLine + "second Line" + Environment.NewLine + "Third line";
        List<String> errorMessageList = new List<string>();

        Mock<IPathReader> mock = new Mock<IPathReader>();
        mock.Setup(x => x.CreateReader(It.IsAny<string>())).Returns(new StringReader(testString));

        IOManager testObject = new IOManager(mock.Object);

        int i = testObject.GetLastRowInFile(testString, errorMessageList);              //Replace with It.IsAny<string>()
        Assert.AreEqual(i, 3);
        Assert.AreEqual(errorMessageList.Count, 0);
    }
    public void GetLastRowInFile_ReturnsNumberOfRows_Returns3()
    {
        StubGetLastRowInFile myStub = new StubGetLastRowInFile();
        List<String> errorMessageList = new List<string>();
        IOManager testObject = new IOManager(myStub);
        int i = testObject.GetLastRowInFile(It.IsAny<string>(), errorMessageList);
        Assert.AreEqual(i, 3);
        Assert.AreEqual(errorMessageList.Count, 0);
    }
public class StubGetLastRowInFile : IPathReader
{
    public TextReader CreateReader(string path)
    {
        //string testString = "first Row" + Environment.NewLine + "second Line" + Environment.NewLine + "Third line";
        string testString = "04/01/2010 00:00,1.4314,1.4316";
        UTF8Encoding encoding = new UTF8Encoding();
        UnicodeEncoding uniEncoding = new UnicodeEncoding();

        byte[] testArray = encoding.GetBytes(testString);

        MemoryStream ms = new MemoryStream(testArray);

        StreamReader sr = new StreamReader(ms);

        return sr;
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Data;
using System.Globalization;
using System.Collections;
using System.Reflection;
using System.ComponentModel;

namespace FrazerMann.CsvImporter.Entity
{
    public interface IPathReader
    {
        TextReader CreateReader(string path);
    }

    public class PathReader : IPathReader
    {
        public TextReader CreateReader(string filePath)
        {
            return new StreamReader(filePath);
        }
    }


public interface IIOManager
{
    Stream OpenFile(string path);

    int GetLastRowInFile(string filePath, List<String> errorMessageList);

    int GetNumberOfColumnsInFile(string filePath, List<string> errorMessageList);

    bool IsReadOnly(string filePath);
}


public class IOManager : IIOManager
{
    private IPathReader _reader;

    public IOManager(IPathReader reader)
    {
        this._reader = reader;
    }


    public Stream OpenFile(string path)
    {
        return new FileStream(path, FileMode.Open);
    }


    public int GetNumberOfColumnsInFile(string filePath, List<String> errorMessageList)
    {
        int numberOfColumns = 0;
        string lineElements;

        try
        {
            using (StreamReader columnReader = (StreamReader)_reader.CreateReader(filePath))
            {
                lineElements = columnReader.ReadLine();
                string[] columns = lineElements.Split(',');
                numberOfColumns = columns.Length;
            }
        }
        catch (Exception ex)
        {
            errorMessageList.Add(ex.Message);
            numberOfColumns = -1;
        }
        return numberOfColumns;
    }


    public int GetLastRowInFile(string filePath, List<String> errorMessage)
    {
        int numberOfRows = 0;
        string dataRow;

        try
        {
            using (StreamReader rowReader = (StreamReader)_reader.CreateReader(filePath))
            {
                while ((rowReader.Peek()) > -1)
                {
                    dataRow = rowReader.ReadLine();
                    numberOfRows++;
                }
                return numberOfRows;
            }
        }
        catch (Exception ex)
        {
            errorMessage.Add(ex.Message);
            return -1;
        }
    }


    public bool IsReadOnly(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.IsReadOnly;
    }
}


public interface IVerificationManager
{
    void ValidateCorrectExtension(string filePath, List<String> errorMessageList);

    void ValidateAccessToFile(string filePath, List<String> errorMessageList);

    void ValidateNumberOfColumns(string filePath, int dataTypeCount, List<String> errorMessageList);

    int ValidateFinalRow(int finalRow, string filePath, List<String> errorMessageList);

    void ValidateRowInputOrder(int initialRow, int finalRow, List<String> errorMessageList);

    void EnumeratedDataTypes(UserInputEntity inputs, List<String> errorMessageList);

    int GetProgressBarIntervalsForDataVerification(int initialRow, int finalRow, List<String> errorMessageList);
}


public class VerificationManager : IVerificationManager
{
    private IIOManager _iomgr;

    public VerificationManager(IIOManager ioManager)
    {
        this._iomgr = ioManager;
    }

    public void ValidateCorrectExtension(string filePath, List<String> errorMessageList)
    {
        if (filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) | filePath.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) { }
        else
        {
            errorMessageList.Add("Selected file does not have a compatable extension.");
        }
    }

    public void ValidateAccessToFile(string filePath, List<String> errorMessageList)
    {
        try
        {

            if (_iomgr.IsReadOnly(filePath) == true) { }
            else
            {
                errorMessageList.Add("Can not read/write to the specified file.");
            }
        }
        catch (Exception e)
        {
            errorMessageList.Add(e.Message);
        }
    }

    public void ValidateNumberOfColumns(string filePath, int userSpecifiedColumnCount, List<String> errorMessageList)
    {
        int numberOfColumnsInFile = _iomgr.GetNumberOfColumnsInFile(filePath, errorMessageList);

        if (userSpecifiedColumnCount != numberOfColumnsInFile) errorMessageList.Add("Number of columns specified does not match number present in file.");
    }

//**TEST APPLIES HERE**

    public int ValidateFinalRow(int finalRow, string filePath, List<String> errorMessageList)
    {
        int totalNumberOfRowsInFile = 0;

        totalNumberOfRowsInFile = _iomgr.GetLastRowInFile(filePath, errorMessageList);

        if (totalNumberOfRowsInFile != -1)
        {
            if (finalRow == 0)
            {
                return totalNumberOfRowsInFile;
            }
            else
            {
                if (finalRow > totalNumberOfRowsInFile)
                {
                    errorMessageList.Add("Specified 'Final Row' value is greater than the total number of rows in the file.");
                }
            }
        }
        return 0;
    }

    public void ValidateRowInputOrder(int initialRow, int finalRow, List<String> errorMessageList)
    {
        if (initialRow > finalRow)
        {
            errorMessageList.Add("Initial row is greater than the final row.");
        }
    }

    public void EnumeratedDataTypes(UserInputEntity inputs, List<String> errorMessageList)
    {
        inputs.EnumeratedDataTypes = new int[inputs.DataTypes.Count];
        try
        {
            for (int i = 0; i < inputs.DataTypes.Count; i++)
            {
                inputs.EnumeratedDataTypes[i] = (int)Enum.Parse(typeof(Enumerations.ColumnDataTypes), inputs.DataTypes[i].ToUpper());
            }
        }
        catch (Exception ex)
        {
            errorMessageList.Add(ex.Message);
        }
    }

    public int GetProgressBarIntervalsForDataVerification(int initialRow, int finalRow, List<String> errorMessageList)
    {
        int progressBarUpdateInverval = -1;

        try
        {
            int dif = (finalRow - initialRow) + 1;
            progressBarUpdateInverval = dif / 100;

            if (progressBarUpdateInverval == 0)
            {
                progressBarUpdateInverval = 1;
            }
        }
        catch (Exception ex)
        {
            errorMessageList.Add(ex.Message);
        }
        return progressBarUpdateInverval;
    }
}



public class EntityVerification
{

    private VerificationManager _vmgr;

    public EntityVerification(VerificationManager vManager)
    {
        this._vmgr = vManager;
    }


    public void VerifyUserInputManager(UserInputEntity inputs, List<string> errorMessageList)
    {
        _vmgr.ValidateCorrectExtension(inputs.CsvFilePath ,errorMessageList);
        _vmgr.ValidateCorrectExtension(inputs.ErrorLogFilePath, errorMessageList);

        _vmgr.ValidateAccessToFile(inputs.CsvFilePath, errorMessageList);
        _vmgr.ValidateAccessToFile(inputs.ErrorLogFilePath, errorMessageList);

        _vmgr.ValidateNumberOfColumns(inputs.CsvFilePath, inputs.DataTypes.Count, errorMessageList);

        inputs.FinalRow = _vmgr.ValidateFinalRow(inputs.FinalRow, inputs.CsvFilePath, errorMessageList);

        _vmgr.ValidateRowInputOrder(inputs.InitialRow, inputs.FinalRow, errorMessageList);

        _vmgr.EnumeratedDataTypes(inputs, errorMessageList);

        inputs.ProgressBarUpdateIntervalForDataVerification = _vmgr.GetProgressBarIntervalsForDataVerification(inputs.InitialRow, inputs.FinalRow, errorMessageList);
    }
}
}
    [Test]
    public void ValidateFinalRow_FinalRowReturned_Returns6()
    {
        List<String> errorMessageList = new List<string>();                             //Remove if replaced

        Mock<IIOManager> mock = new Mock<IIOManager>();
        mock.Setup(x => x.GetLastRowInFile(It.IsAny<String>(), errorMessageList)).Returns(6);

        VerificationManager testObject = new VerificationManager(mock.Object);
        int i = testObject.ValidateFinalRow(0, "Random", errorMessageList);             //Replace with It.IsAny<string>()  and It.IsAny<List<string>>()
        Assert.AreEqual(i, 6);
    }