我正在尝试使用C#和JSON.NET将数据写入json文件中,并参考此处建议的接受答案(How to write a JSON file in C#?)。 当我运行下面的代码时,我没有收到任何错误消息,但是数据也没有写入json文件。
在功能上我要实现的是创建一个json文件,该文件存储执行Nunit测试时执行的操作的时间
我已经尝试实施此处(Deserializing JSON data to C# using JSON.NET)建议的解决方案,但是并不能解决我的问题
public static class ActionTimeHelper
{
private static readonly string _actionTimeLogFileName = "ActionTimeLog_" + string.Format("{0:yyyy_MM_dd_hhmmss}", DateTime.Now);
[ThreadStatic] private static FileStream _fileStream = null;
[ThreadStatic] private static StreamWriter _actionStreamWriter = null;
[ThreadStatic] private static JsonWriter _jsonWriter = null;
[ThreadStatic] private static List<ActionTimeInfo> actionList = new List<ActionTimeInfo>();
public static void CreateActionTimeLogFile(string logPath, string testName)
{
string dir = logPath + testName + @"\";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
_fileStream = File.Open(dir + _actionTimeLogFileName + ".json", FileMode.CreateNew);
_actionStreamWriter = new StreamWriter(_fileStream);
_jsonWriter = new JsonTextWriter(_actionStreamWriter);
_jsonWriter.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(_jsonWriter, actionList.ToArray().ToString());
//var jarray = JsonConvert.DeserializeObject<List<ActionTimeInfo>>(actionList.ToArray().ToString());
}
public static void StartActionTime(string actionName)
{
actionList.Add(new ActionTimeInfo()
{
ActionName = actionName,
StartTime = DateTime.Now
});
}
public static void EndActionTime(string actionName)
{
ActionTimeInfo endAction = actionList.Find(actionInfo => actionInfo.ActionName.Equals(actionName));
endAction.EndTime = DateTime.Now;
endAction.ExecutionTime = endAction.EndTime.Subtract(endAction.StartTime);
}
}
public class ActionTimeInfo
{
public string ActionName { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public TimeSpan ExecutionTime { get; set; }
}
在UUnit测试中使用上述类:
[Test, Parallelizable, RequiresThread]
public void TestMethod3()
{
ActionTimeHelper.StartActionTime("Login Action");
ActionTimeHelper.EndActionTime("Login Action");
}
[TearDown]
public void TestTearDown()
{
ActionTimeHelper.CreateActionTimeLogFile(TCRunSettings.LogPath, TestContext.CurrentContext.Test.Name);
}
实际结果:在目录中创建了JSON文件,但未写入任何列表项 预期结果:在目录中创建的JSON文件以及写入其中的列表项
答案 0 :(得分:0)
我认为您缺少_jsonWriter的刷新和关闭功能?
也许尝试
_jsonWriter.Flush();
_jsonWriter.Close();
方法末尾
甚至更好,使用using来包装_fileStream,_actionStreamWriter和_jsonWriter