This question already has an answer here:
- Easiest way to read from and write to files 10 answers
I am trying to write a unit test to make sure that the method is writing to a text file. My method writes to the text file MovieList.txt
. I kept getting an error saying that it cannot access the file because it is being used by another process. So I tried changing the method to accept a parameter to write to a different text file, MovieListTEST.txt
, but I still can't figure it out. Anyone know how to properly do this?
This is my code to write to the file:
public bool WriteMovieListToFile()
{
try
{
FileStream fs = new FileStream("MovieList.txt", FileMode.Append, FileAccess.Write);
StreamWriter textWriter = new StreamWriter(fs);
textWriter.WriteLine(movie.Title);
textWriter.WriteLine(movie.Genre);
textWriter.WriteLine(movie.Actor);
textWriter.WriteLine(movie.Year);
textWriter.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
return false;
}
}
Edited with param:
public bool WriteMovieListToFile(string fileLocation)
{
try
{
FileStream fs = new FileStream(fileLocation, FileMode.Append, FileAccess.Write);
StreamWriter textWriter = new StreamWriter(fs);
This is my unit test code:
/// <summary>
///A test for WriteMovieListToFile
///</summary>
[TestMethod()]
public void WriteMovieListToFileTest1()
{
Movie movie1 = new Movie("Title", "Genre", "Actor", "Year");
movieSystem.AddMovie(movie1);
movieSystem.WriteMovieListToFile("MovieListTEST.txt");
var fileText = File.ReadLines("MovieListTEST.txt");
Assert.IsTrue(fileText.ToString().Length > 1);
}
Aucun commentaire:
Enregistrer un commentaire