我有以下代码:
private void SetControlNumbers()
{
string controlString = "";
int numberLength = PersonNummer.Length;
switch (numberLength)
{
case (10) :
controlString = PersonNummer.Substring(6, 4);
break;
case (11) :
controlString = PersonNummer.Substring(7, 4);
break;
case (12) :
controlString = PersonNummer.Substring(8, 4);
break;
case (13) :
controlString = PersonNummer.Substring(9, 4);
break;
}
ControlNumbers = Convert.ToInt32(controlString);
}
使用以下测试方法测试:
[TestMethod()]
public void SetControlNumbers_Length10()
{
string pNummer = "9999999999";
Personnummer target = new Personnummer(pNummer);
Assert.AreEqual(9999, target.ControlNumbers);
}
[TestMethod()]
public void SetControlNumbers_Length11()
{
string pNummer = "999999-9999";
Personnummer target = new Personnummer(pNummer);
Assert.AreEqual(9999, target.ControlNumbers);
}
[TestMethod()]
public void SetControlNumbers_Length12()
{
string pNummer = "199999999999";
Personnummer target = new Personnummer(pNummer);
Assert.AreEqual(9999, target.ControlNumbers);
}
[TestMethod()]
public void SetControlNumbers_Length13()
{
string pNummer = "1999999-9999";
Personnummer target = new Personnummer(pNummer);
Assert.AreEqual(9999, target.ControlNumbers);
}
出于某种原因,Visual Studio说我有一个未经测试的块,尽管在测试中的所有代码都显示为蓝色(即代码在我的单元测试中有所涉及)。这是因为我没有在交换机中定义的默认值吗?调用SetControlNumbers()方法时,已对其运行的字符串进行了验证并检查它是否符合规范,并且交换机中的各种Substring调用将生成包含4个字符的字符串。我只是好奇为什么它说有一个未经测试的块。我根本不是单元测试专家,所以我很想得到一些反馈。
另外,除了添加try-catch块并检查FormatExceptions和OverflowExceptions之外,如何在切换后改进转换以使其更安全?
答案 0 :(得分:3)
您需要在switch语句中添加一个默认部分,以捕获未明确定义的情况。
private void SetControlNumbers()
{
string controlString = "";
int numberLength = PersonNummer.Length;
switch (numberLength)
{
case (10) :
controlString = PersonNummer.Substring(6, 4);
break;
case (11) :
controlString = PersonNummer.Substring(7, 4);
break;
case (12) :
controlString = PersonNummer.Substring(8, 4);
break;
case (13) :
controlString = PersonNummer.Substring(9, 4);
break;
default:
//decide what to do here,
//could do this or something more appropriate for your situation
throw new NotSupportedException("An invalid PersonNummer.Length value was encountered.")
}
ControlNumbers = Convert.ToInt32(controlString);
}