Jac*_*ope 1 c# dependencies nunit unit-testing
我有一些代码执行一些遗留的"数据库"操作,然后处理结果.我想编写一个单元测试来检查调用遗留代码的方法,而不与"数据库"交互.
我的代码看起来像这样:
public static bool CallRoutine(LegacySession session, /* routine params*/)
{
try
{
LegacyRoutine routine = session.CreateRoutine(/* routine params */);
routine.Call();
// Process result
}
catch (LegacyException ex)
{
// Perform error handling
}
}
Run Code Online (Sandbox Code Playgroud)
如果这是我的所有代码,我将创建接口,然后使用MOQ或类似的东西创建LegacySession并LegacyRoutine使用这些接口的模拟实现来编写单元测试.问题是,我没有访问代码,LegacyRoutine或者LegacySession,所以我不能让他们实现一个接口.
关于如何在不改变生产代码的情况下做到这一点的任何想法?
如果您无法访问LegacyRoutine(我猜它在引用的DLL中),为什么不为它创建一个包装器,然后轻弹/关闭不同的实现:
public interface ILegacyWrapper
{
ILegacyRoutine CreateRoutine();
// etc etc
}
public interface ILegacyRoutine
{
// put members of LegacyRoutine
}
Run Code Online (Sandbox Code Playgroud)
明白我的意思了吗?只需将所有内容都模拟为包装器/接口.
然后你可以去:
ILegacyRoutine routine = session.CreateRoutine(/* routine params */)
Run Code Online (Sandbox Code Playgroud)
当会话将被声明为ILegacyWrapper,但有一个模拟的具体实现.
此外,它不言而喻(但无论如何我会说),你应该考虑一个DI框架,让你的生活更简单.否则你将IFoo foo = new Foo()在整个地方以(硬编码注射)结束.
StructureMap是我选择的DI毒药.
HTH