I have a method that serialises a Json object shown below:
public bool SerializeObject<T>(string fileName, IEnumerable<T> list)
{
try
{
var listContent = JsonConvert.SerializeObject(list, Formatting.Indented);
var relativeFileName = _httpContext.Server.MapPath(fileName);
_file.WriteAllText(relativeFileName, listContent);
return true;
}
catch (Exception ex)
{
_logger.LogException(ex);
return false;
}
}
I want to create a unit test to test if the method returns true but cannot think of the logic to do this for a unit test! can anyone make some suggestions to how I do this in xUnit? Thanks
[Fact]
public void SerializeObject_CorrectData_ReturnsTrue()
{
//arrange
string fileName = "blah.txt";
var collect = new List<MyObject>{//add stuff};
//act
//nothing here
//assert
Assert.True(SerializeObject<MyObject>(fileName, collect));
}
This is basically what you are looking for. You will want to read about mocking to make sure you are correctly isolating your tests to simple units; instead of testing system components. You should not unit test your method, webserver, and logger at the same time, that will lead to a bad experience and unmaintainable test.
If you are a book person, I highly recommend Osherove's The Art of Unit Testing, it is a very quick book and has proven invaluable to me.