本文介绍了无法覆盖1行如果声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞!private object ReadNextObject() {if (currentLine == null)return null;// Check to see if the next value is quotedbool quoted = false;if (currentLine.StartsWith("\""))quoted = true;// Find the end of the next valuestring nextObjectString = "";int i = 0;int len = currentLine.Length;bool foundEnd = false;while (!foundEnd && i <= len){// Check if we've hit the end of the stringif ((!quoted && i == len) // non-quoted strings end with a comma or end of line|| (!quoted && currentLine.Substring(i, 1) == ",")// quoted strings end with a quote followed by a comma or end of line|| (quoted && i == len - 1 && currentLine.EndsWith("\""))|| (quoted && currentLine.Substring(i, 2) == "\","))foundEnd = true;elsei++;}if (quoted){ if (i > len || !currentLine.Substring(i, 1).StartsWith("\"")) throw new FormatException("Invalid CSV format: " + currentLine.Substring(0, i));i++;}nextObjectString = currentLine.Substring(0, i).Replace("\"\"", "\"");if (i < len)currentLine = currentLine.Substring(i + 1);elsecurrentLine = "";if (quoted){if (nextObjectString.StartsWith("\""))nextObjectString = nextObjectString.Substring(1);if (nextObjectString.EndsWith("\""))nextObjectString = nextObjectString.Substring(0, nextObjectString.Length - 1);return nextObjectString;}else{object convertedValue;StringConverter.ConvertString(nextObjectString, out convertedValue);return convertedValue;}}我需要对代码进行单元测试....I Need to Unit Test Above Code....if (i > len || !currentLine.Substring(i, 1).StartsWith("\"")) throw new FormatException("Invalid CSV format: " + currentLine.Substring(0, i));i++;无法掩盖抛出异常......我需要存根或模拟来覆盖这条线......Not able to Cover Throw Exception...Do I Need Stub or Mock to Cover this Line...如果是这样我怎么能这样做..If so how can i Do that..当前测试。public void Test_ReadNextObject_19() { object returnValue = string.Empty; try { privateClass.SetField("currentLine", "\"\"\"\"");privateClass.GetField("currentLine").ToString())); returnValue = privateClass.Invoke("ReadNextObject"); } catch (FormatException ex) { returnValue = ex.Message; } }当前测试用例SetField"" \" \ " \" \"" ..Current Test Case SetField ""\"\"\"\"" ..推荐答案 >> 我需要Stub或Mock来覆盖这条线...... 基于代码"私有对象ReadNextObject()... ",这是一种私人方法。你必须模仿这个私有方法。但是测试私有方法没有意义。因为他们没有公共行为,除了可以通过定义类的公共方法访问的行为,他们的行为应该通过测试公共方法来测试。 是否有其他方法可以调用此私有方法?如果是这样,你可以从你调用的方法写,然后,就不需要模拟了。 另外,请看一下这个帖子"单元测试如何确认异常被抛出": https://stackoverflow.com/questions/6125143/how-can-a-unit-测试 - 确认 - 例外 - 已被抛出 问候, Judyzh 这篇关于无法覆盖1行如果声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 05-28 00:40