Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 测试项目和配置文件_.net_Wcf_Unit Testing - Fatal编程技术网

.net 测试项目和配置文件

.net 测试项目和配置文件,.net,wcf,unit-testing,.net,Wcf,Unit Testing,在我的Visual Studio 2008解决方案中有这样的设置:一个WCF服务项目(WCFService),它使用库(Lib1,它需要app.config文件中的一些配置条目)。我有一个单元测试项目(MSTest),其中包含与Lib1相关的测试。为了运行这些测试,我需要在测试项目中有一个配置文件。有没有办法从WCFService自动加载它,这样我就不需要在两个地方更改配置项?让库在整个代码中直接从app.config文件读取属性会使代码变得脆弱,难以测试。最好有一个类负责读取配置并以强类型方式

在我的Visual Studio 2008解决方案中有这样的设置:一个WCF服务项目(WCFService),它使用库(Lib1,它需要app.config文件中的一些配置条目)。我有一个单元测试项目(MSTest),其中包含与Lib1相关的测试。为了运行这些测试,我需要在测试项目中有一个配置文件。有没有办法从WCFService自动加载它,这样我就不需要在两个地方更改配置项?

让库在整个代码中直接从app.config文件读取属性会使代码变得脆弱,难以测试。最好有一个类负责读取配置并以强类型方式存储配置值。让此类实现一个接口,该接口定义配置中的属性,或者使属性为虚拟属性。然后,您可以模拟这个类(使用Rhinomock之类的框架,或者手工制作一个也实现接口的假类)。将类的实例注入到每个需要通过构造函数访问配置值的类中。将其设置为,如果注入的值为null,那么它将创建适当类的实例

 public interface IMyConfig
 {
      string MyProperty { get; }
      int MyIntProperty { get; }
 }

 public class MyConfig : IMyConfig
 {
      public string MyProperty
      {
         get { ...lazy load from the actual config... }
      }

      public int MyIntProperty
      {
         get { ... }
      }
  }

 public class MyLibClass
 {
      private IMyConfig config;

      public MyLibClass() : this(null) {}

      public MyLibClass( IMyConfig config )
      {
           this.config = config ?? new MyConfig();
      }

      public void MyMethod()
      {
          string property = this.config.MyProperty;

          ...
      }
 }
试验

public void TestMethod()
{
IMyConfig config=MockRepository.GenerateMock();
Expect(c=>c.MyProperty).Return(“stringValue”);
var cls=新的MyLib(配置);
cls.MyMethod();
config.verifyallexpections();
}

您可以在一个(或多个)文件中收集所有配置条目,并使用SectionInformation.ConfigSource属性从WCF服务项目和测试项目指向该文件。
 public void TestMethod()
 {
      IMyConfig config = MockRepository.GenerateMock<IMyConfig>();
      config.Expect( c => c.MyProperty ).Return( "stringValue" );

      var cls = new MyLib( config );

      cls.MyMethod();

      config.VerifyAllExpectations();
 }