我有以下Log方法(用于单元测试项目):
public static void WriteLogFile<T>(T obj, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = "")
{
#if WRITELOGFILE
var path = Path.Combine(LogFileLocation, callingMethod + ".json");
var content = (typeof(T) == typeof(string)) ? (obj as string) : JsonConvert.SerializeObject(obj);
File.WriteAllText(path, content);
#endif
}我在下面的TestMethod中使用了它
[TestMethod]
public async Task TestGetUserInfoAsync()
{
//var tokenFile = TestUtils.GetLogFileLocation(nameof(this.TestRedeemTokensAsync2));
var tokenFile = @"D:\Temp\TestLog\TestRedeemTokensAsync2.json";
var accessToken = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(tokenFile))
.access_token.ToString();
var result = await GoogleService.GetUserInfoAsync(this.systemConfig,
accessToken);
TestUtils.WriteLogFile(result);
Assert.IsNotNull(result);
}我还有其他3个测试方法,它们都能正确运行,而且它们都有异步/等待任务,使用方法名称中的文件名写入日志文件。
但是,对于上述具体方法,参数callingMethod为空字符串(非null)。
为什么会发生这种情况?在这种情况下,我如何调试?
补充信息:我想这可能是因为我添加了以下方法,第一次调用搞砸了:
public static string GetLogFileLocation([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = "")
{
var path = Path.Combine(LogFileLocation, callingMethod + ".json");
return path;
}但是,我尝试删除它并使用硬字符串作为文件路径(正如您在上面的代码中看到的),但问题仍然存在。
我不知道是什么引起的。

EDIT2: IL代码确实有问题:其他4个(对不起,4个,不是3个)的TestMethod运行正常,他们的IL代码是正确的,如下所示:


完整的IL代码在这里:http://pasted.co/cf4b0ea7
发布于 2018-03-19 23:46:00
这个问题似乎是随着async和dynamic的结合而发生的。删除其中一个(切换到同步或转换为强类型变量)来修复问题:
[TestMethod]
public async Task TestGetUserInfoAsync()
{
//var tokenFile = TestUtils.GetLogFileLocation(nameof(this.TestRedeemTokensAsync2));
var tokenFile = @"D:\Temp\TestLog\TestRedeemTokensAsync2.json";
var accessToken = (JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(tokenFile))
.access_token.ToString()) as string; // Here, cast this to string instead of keeping it as dynamic
var result = await GoogleService.GetUserInfoAsync(this.systemConfig,
accessToken);
TestUtils.WriteLogFile(result);
Assert.IsNotNull(result);
}https://stackoverflow.com/questions/49361452
复制相似问题