VS2008单元测试-断言方法退出 [英] VS2008 unit tests - assert method exits

查看:117
本文介绍了VS2008单元测试-断言方法退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用VS 2008的内置单元测试框架编写C#单元测试,而我正在测试的方法称为Environment.Exit(0).当我在单元测试中调用此方法时,单元测试已中止.该方法确实应该在调用Exit,并且我想要一种方法来测试它,并测试它使用的退出代码.我该怎么办?我查看了 Microsoft.VisualStudio.TestTools.UnitTesting命名空间,但看不到任何相关内容.

I'm trying to write a C# unit test with VS 2008's built-in unit testing framework and the method I'm testing calls Environment.Exit(0). When I call this method in my unit test, my unit test is Aborted. The method should indeed be calling Exit, and I want a way to test that it does, and also to test the exit code that it uses. How might I do this? I looked at Microsoft.VisualStudio.TestTools.UnitTesting Namespace but didn't see anything that looked relevant.

[TestMethod]
[DeploymentItem("myprog.exe")]
public void MyProgTest()
{
    // Want to ensure this Exit's with code 0:
    MyProg_Accessor.myMethod();
}

同时,这是我要测试的代码的要点:

Meanwhile, here's the gist of the code that I want to test:

static void myMethod()
{
    Environment.Exit(0);
}

这是我在测试方法中使用的解决方案,这要感谢

here's the solution I used in my test method, thanks to RichardOD:

Process proc;

try
{
    proc = Process.Start(path, myArgs);
}
catch (System.ComponentModel.Win32Exception ex)
{
    proc = null;
    Assert.Fail(ex.Message);
}

Assert.IsNotNull(proc);
proc.WaitForExit(10000);
Assert.IsTrue(proc.HasExited);
Assert.AreEqual(code, proc.ExitCode);

推荐答案

这听起来像是一个非常糟糕的主意.显然,Environment.Exit(0)会按规定执行,因此为什么单元测试会中断.

This sounds like an incredibly bad idea. Environment.Exit(0), will obviously do as prescribed, hence why your unit testings are breaking.

如果您真的仍然想测试它,可以通过启动一个单独的过程并检查返回代码,看看将其包装在

If you really want to still test this you can by launching a seperate process and checking the return code- have a look at wrapping it up in Process.Start.

我猜另一个选择是将此代码分解出来并注入测试间谍,或使用一个模拟对象以验证正确的行为.

I guess another option is factoring this code out and injecting a test spy, or using a mock object to verify correct behaviour.

也许您可以使用Typemock隔离器执行某些操作-我相信这可以让您

Perhaps you can do something with Typemock Isolator- I believe this lets you mock static methods.

这篇关于VS2008单元测试-断言方法退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆