在C#中测试Environment.Exit() [英] Test Environment.Exit() in C#
本文介绍了在C#中测试Environment.Exit()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#中是否存在Java中 ExpectedSystemExit
的某种等效形式?我的代码中有一个出口,非常希望能够对其进行测试.我在C#中发现的唯一问题是变通办法.
Is there in C# some kind of equivalent of ExpectedSystemExit
in Java? I have an exit in my code and would really like to be able to test it. The only thing I found in C# is a not really nice workaround.
示例代码
public void CheckRights()
{
if(!service.UserHasRights())
{
Environment.Exit(1);
}
}
测试代码
[TestMethod]
public void TestCheckRightsWithoutRights()
{
MyService service = ...
service.UserHasRights().Returns(false);
???
}
我正在使用VS框架进行测试(+ NSubstitute进行模拟),但是切换到nunit或进行此测试的任何问题都不是问题.
I am using the VS framework for testing (+ NSubstitute for mocking) but it is not a problem to switch to nunit or whatever for this test.
推荐答案
我最终创建了一个新方法,然后可以在测试中进行模拟.
I ended up creating a new method which I can then mock in my tests.
代码
public void CheckRights()
{
if(!service.UserHasRights())
{
Environment.Exit(1);
}
}
internal virtual void Exit()
{
Environment.Exit(1);
}
单元测试
[TestMethod]
public void TestCheckRightsWithoutRights()
{
MyService service = ...
service.When(svc => svc.Exit()).DoNotCallBase();
...
service.CheckRights();
service.Received(1).Exit();
}
这篇关于在C#中测试Environment.Exit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文