I have a method which constructs a string from List
. I want to test the method with a unit test. What's a good way to test that method?
I need to use the database to get matchList. I don't know how to use a mock object to do that.
public class File_IO
{
private string _rootDirectory;
private string _taskName;
private File_IO()
{
}
public File_IO(string rootDirectory, string taskName)
{
_rootDirectory = rootDirectory;
_taskName = taskName;
}
public string RootDir
{
get { return _rootDirectory; }
}
public string TaskName
{
get { return _taskName; }
}
public string constructString()
{
string result = string.Empty;
string pipe = "|";
StringBuilder stringBuilder = new StringBuilder();
bool isFirst = true;
IList matchList = new List<string> { "*.Ext","*.ext" };
// Iterate over the results and construct the string.
foreach (var item in matchList)
{
if (!isFirst)
{
stringBuilder.Append(pipe);
}
isFirst = false;
stringBuilder.Append(item);
}
result = stringBuilder.ToString();
return result;
}
}
Nunit is a pretty popular framework to do unit testing in C#. http://nunit.org/
Use nuget to install it and create your test cases. It'll look more or less like this:
[Test]
public static void TestFile_IO()
{
var expectedString = "what ever is supposed to come out of the method";
var result = new File_IO.constructString();
Assert.AreEqual(expectedString, result)
}
I'm not sure if I understand question correctly or not... May be you need something like this:
interface IRepository
{
List<string> GetList();
}
class Repository
{
List<string> GetList() { return /*Query database here*/ ;}
}
public class File_IO
{
private IRepository _repository;
private File_IO(IRepository repository)
{
_repository = repository;
}
public string constructString()
{
IList matchList = _repository.GetList();
.........................
return result;
}
}
In this case you will be able to test this using one of mock frameworks (Moq, NSubstitute). Example below use NSubstitute.
public void TestMethod()
{
var repositoryMock = Substitute.For<IRepository>();
repositoryMock.GetList().Returns(new List<string> {"str1", "str2"});
var f_io = new File_IO(repositoryMock);
var result = f_io.constructString();
Assert.AreEqual("Expected string", result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.