【发布时间】:2018-07-04 16:22:23
【问题描述】:
我现在正在设计一些代码,如果字符串参数为 null 或为空,我将抛出异常,并且异常被抛出,但是当我在 UnitTesting 时它没有被捕获。
这是我正在使用的客户端。
public class PipeClient : IPipeClient
{
public async void Send(string host, string pipeName, Message msg)
{
if (string.IsNullOrEmpty(msg.PreparedMessage))
throw new ArgumentException("MESSAGE_NOT_FOUND");
if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(pipeName))
throw new ArgumentNullException();
if (!host.TryParseHost())
throw new ArgumentException("INVALID_HOST_NAME");
using (var pipeClient = new NamedPipeClientStream(host, pipeName, PipeDirection.Out))
{
pipeClient.Connect(200);
using (var writer = new StreamWriter(pipeClient))
{
await Task.Run(() => writer.WriteLine(msg.PreparedMessage));
writer.Flush();
}
}
}
}
这是单元测试
[TestMethod]
public void Send_FailsOnWrongHostName()
{
var name = "FailWithHostname";
var msg = new Message(MyStates.Register, "UnitTest", "Test");
try
{
var client = new PipeClient();
client.Send("lol", name, msg);
}
catch (Exception e)
{
Assert.IsTrue(e is ArgumentException);
}
}
因此,据我所知,当我运行该测试时,它应该在我调用 Send 方法(确实如此)时抛出异常,然后在 catch 子句中被捕获,因为我没有在 PipeClient 中捕获它。然而它没有,它只是以失败的测试退出。
如果您需要更多信息,请告诉我,提前致谢。
【问题讨论】:
-
您不需要捕获和测试异常。如果您希望发生异常,请在您的
[TestMethod]上方添加[ExpectedException(typeof(ArgumentException)符号。 -
我之前尝试过但没有成功,这就是我尝试这种方法的原因。我得到它没有抛出异常的错误,我不明白。
-
我当然已经通过调试确认该方法实际上是在抛出预期的异常。
-
好像被别的东西抓住了一样。
-
您确定抛出的异常实际上是 ArgumentException 吗?当查看您的代码并假设确实发生了异常时,我唯一能想到的是您的 Send 方法中的某些方法调用引发了一些与 ArgumentException 不同类型的异常。