单元测试遗留 C# 代码
如何为这样的方法编写 NUnit 测试。这个方法本身是否值得重构? 处理遗留代码中的此类场景的最佳方法是什么?
public bool DoXYZ()
{
ABC abc= new ABC()
XYZ xyz = new XYZ();
if (xyz .IsSomeCondition(Session.SessionID))
{ return false; }
else
{ return abc.IsSomeOtherCondition(SessionID.SessionID); }
}
How to write a NUnit test for a method like this. Does this method itself warrant refactoring?
What is the best approach to deal with scenarios like this in leagacy code?
public bool DoXYZ()
{
ABC abc= new ABC()
XYZ xyz = new XYZ();
if (xyz .IsSomeCondition(Session.SessionID))
{ return false; }
else
{ return abc.IsSomeOtherCondition(SessionID.SessionID); }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能需要重构它以引入用于依赖项注入的钩子。例如,包含 DoXYZ 方法的类可以获得 ABC 和 XYZ 的新属性。这些属性可以默认为 ABC 和 XYZ 的实例,但在单元测试中可以替换为模拟版本。
如果您更喜欢使用 IoC,这种方法也支持
You will probably need to refactor it to introduce hooks for dependency injection. For example, the class that contains the DoXYZ method can get new properties for ABC and XYZ. These properties could default to instances of ABC and XYZ, but in the unit tests could be replaced by mock versions.
And if you prefer to use IoC, this approach supports that as well
我肯定会重构以通过参数注入会话 ID - 否则您将必须手动创建会话。
可以做成静态的吗?看起来很像,特别是当您注入 sessionid 时。
另外,您正在实现一个(短)命令调度程序,与 IoC 相比,它通常被认为是一种反模式(请参见上面 Joel Martinez 的回答)。
I would definitely refactor to inject the session id via a parameter - otherwise you'll have to create the session manually.
Can it be made static? Looks like it, particularly if you inject sessionid.
Also, you're implementing a (short) command dispatcher, which is generally considered an anti-pattern, compared to IoC (see Joel Martinez' answer above).
您有两种选择:
处理大型遗留代码的方法可能是同时使用这两种方法。
您还可以查看 MSDN 杂志中的这篇文章。
You have two choices:
The way to go in big legacy code is probably using both approaches.
You can also check this article from MSDN magazine.
考虑到问题中的混淆代码,我只能提供一些
。
Given the obfuscated code in the question, I can only offer a few pointers
.