如何在仅更改依赖项的同时运行相同的testmethods?

Dab*_*rnl 4 .net testing dependencies visual-studio-2008

我有5个测试方法来测试PasswordManager对象的功能.我使用visual studio 2008的内置测试引擎.这个管理器可以使用两个依赖项:XMLStorageManager或DbStorageManager.Dependency在Passwordmanager的构造函数中设置.如何运行测试两次,唯一不同的是我使用的StorageManager类型?

(我知道,我知道,这些不是单元测试...)

Mar*_*son 5

我不是MSTest用户,但你可能有一些选择.通常使用NUnit我会使用通用或参数化夹具,但我不确定MSTest是否具有类似功能.鉴于此,以下是我如何使用NUnit执行此操作,其形式应该可以通过模板方法模式使用任何单元测试框架进行重现.

脚步:

  • 定义一个包含所有测试的抽象基类
  • 放入一个名为CreateStorageManager()的抽象方法,它返回一个IStorageManager(或两个依赖项实现的任何接口)
  • 将夹具子类化两次并提供CreateStorageManager()的实现,该实现返回您希望用于运行测试的具体类型.

这是等效NUnit版本的代码; 我相信你可以推断出来. 注意: MSTest的继承规则可能与我以前的略有不同.如果它不起作用,您可以尝试将基类标记为测试夹具.

public abstract class PasswordManagerFixtureBase
{
     protected abstract IStorageManager CreateStorageManager();

     // all tests go in this fixture
     [Test]
     public void SomeTestOrOther()
     { 
         var passwordManager = CreatePasswordManager();

         // do test logic

     }

     private PasswordManager CreatePasswordManager()
     { 
          // calls into subclass implementation to get instance of storage
          IStorageManager storage = CreateStorageManager();
          return new PasswordManager(storage);
     }   
}

// Runs the tests in the fixture base using XmlStorageManager
[TestFixture]
public class PasswordManager_XMLStorageManagerImplTests
{
      protected override IStorageManager CreateStorageManager()
      {
          return new XMLStorageManager();
      }
}

// Runs the tests in the fixture base using DbStorageManager
[TestFixture]
public class PasswordManager_DbStorageManagerImplTests
{
      protected override IStorageManager CreateStorageManager()
      {
          return new DbStorageManager();
      }
}
Run Code Online (Sandbox Code Playgroud)

使用MSTest可能有更优雅的方法,但这应该有效.