development

단위 테스트 프로젝트가 대상 응용 프로그램의 app.config 파일을로드 할 수 있습니까?

big-blog 2020. 6. 18. 07:25
반응형

단위 테스트 프로젝트가 대상 응용 프로그램의 app.config 파일을로드 할 수 있습니까?


app.config 파일을 사용하여 구성 속성을로드하는 .NET 응용 프로그램 (.exe)을 단위로 테스트하고 있습니다. 단위 테스트 응용 프로그램 자체에는 app.config 파일이 없습니다.

구성 속성 중 하나를 사용하는 메서드를 단위 테스트하려고하면 null이 반환 됩니다. 단위 테스트 응용 프로그램이 대상 응용 프로그램의 app.config에로드되지 않기 때문이라고 가정합니다.

이것을 재정의하는 방법이 있습니까? 아니면 대상 app.config의 내용을 로컬 app.config에 복사하는 스크립트를 작성해야합니까?

게시물 종류는이 질문을하지만 저자는 실제로 내가 아닌 다른 각도에서 그것을보고 있습니다.

편집 : 단위 테스트에 VS08 Team System을 사용하고 있다고 언급해야합니다.


가장 간단한 방법은 .config단위 테스트의 배포 섹션에 파일 을 추가하는 것 입니다.

이렇게하려면 .testrunconfig솔루션 항목에서 파일을 엽니 다 . 배치 섹션 .config에서 프로젝트의 빌드 디렉토리 (아마도 bin\Debug) 출력 파일을 추가하십시오 .

배포 섹션에 나열된 모든 항목은 테스트를 실행하기 전에 테스트 프로젝트의 작업 폴더에 복사되므로 구성 종속 코드가 정상적으로 실행됩니다.

편집 : 추가하는 것을 잊었습니다. 모든 상황에서 작동하지는 않으므로 .config단위 테스트의 이름과 일치하도록 출력의 이름을 바꾸는 시작 스크립트를 포함해야 할 수도 있습니다 .


Visual Studio 2008에서는 app.config파일을 테스트 프로젝트에 기존 항목으로 추가하고 파일이 복제되지 않도록 링크로 사본을 선택했습니다. 그렇게하면 솔루션에 사본이 하나만 있습니다. 여러 테스트 프로젝트를 통해 정말 편리합니다!

기존 항목 추가

링크로 추가


사용하든 팀 시스템 테스트 또는 NUnit과를 , 가장 좋은 방법은 테스트를 위해 별도의 클래스 라이브러리를 만드는 것입니다. 테스트 프로젝트에 App.config를 추가하면 컴파일 할 때 자동으로 bin 폴더에 복사됩니다 .

코드가 특정 구성 테스트에 의존하는 경우, 내가 작성하는 첫 번째 테스트는 구성 파일이 사용 가능한지 검증합니다 ( 내가 미친 것이 아니라는 것을 알 수 있습니다 ).

<configuration>
   <appSettings>
       <add key="TestValue" value="true" />
   </appSettings>
</configuration>

그리고 테스트 :

[TestFixture]
public class GeneralFixture
{
     [Test]
     public void VerifyAppDomainHasConfigurationSettings()
     {
          string value = ConfigurationManager.AppSettings["TestValue"];
          Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
     }
}

이상적으로는 구성 개체가 클래스로 전달되도록 코드를 작성해야합니다. 이를 통해 구성 파일 문제와 분리 될뿐만 아니라 다양한 구성 시나리오에 대한 테스트를 작성할 수도 있습니다.

public class MyObject
{
     public void Configure(MyConfigurationObject config)
     {
          _enabled = config.Enabled;
     }

     public string Foo()
     {
         if (_enabled)
         {
             return "foo!";
         }
         return String.Empty;
     }

     private bool _enabled;
}

[TestFixture]
public class MyObjectTestFixture
{
     [Test]
     public void CanInitializeWithProperConfig()
     {
         MyConfigurationObject config = new MyConfigurationObject();
         config.Enabled = true;

         MyObject myObj = new MyObject();
         myObj.Configure(config);

         Assert.AreEqual("foo!", myObj.Foo());
     }
}

예를 들어 웹 응용 프로그램 및 테스트 프로젝트가 포함 된 솔루션이있는 경우 테스트 프로젝트가 웹 응용 프로그램의 web.config를 사용하는 것이 좋습니다.

이를 해결하는 한 가지 방법은 web.config를 복사하여 프로젝트를 테스트하고 app.config로 이름을 바꾸는 것입니다.

또 다른 더 나은 솔루션은 빌드 체인을 수정하고 프로젝트 출력 디렉토리를 테스트하기 위해 web.config의 자동 사본을 만드는 것입니다. 이를 수행하려면 애플리케이션 테스트를 마우스 오른쪽 단추로 클릭하고 특성을 선택하십시오. 이제 프로젝트 속성을 볼 수 있습니다. "이벤트 빌드"를 클릭 한 다음 "포스트 빌드 편집 ..."버튼을 클릭하십시오. 다음 줄을 작성하십시오.

copy "$(SolutionDir)\WebApplication1\web.config" "$(ProjectDir)$(OutDir)$(TargetFileName).config"

And click OK. (Note you most probably need to change WebApplication1 as you project name which you want to test). If you have wrong path to web.config then copy fails and you will notice it during unsuccessful build.

Edit:

To Copy from the current Project to the Test Project:

copy "$(ProjectDir)bin\WebProject.dll.config" "$(SolutionDir)WebProject.Tests\bin\Debug\App.Config"

This is a bit old but I found a better solution for this. I was trying the chosen answer here but looks like .testrunconfig is already obsolete.

1. For Unit Tests, Wrap the config is an Interface (IConfig)

for Unit tests, config really shouldn't be part of what your testing so create a mock which you can inject. In this example I was using Moq.

Mock<IConfig> _configMock;
_configMock.Setup(config => config.ConfigKey).Returns("ConfigValue");
var SUT = new SUT(_configMock.Object);

2. For Integration test, dynamically add the config you need

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if(config.AppSettings.Settings[configName] != null)
{
    config.AppSettings.Settings.Remove(configName);
}
config.AppSettings.Settings.Add(configName, configValue);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");

This is very easy.

  • Right click on your test project
  • Add-->Existing item
  • You can see a small arrow just beside the Add button
  • Select the config file click on "Add As Link"

If you are using NUnit, take a look at this post. Basically you'll need to have your app.config in the same directory as your .nunit file.


If you application is using setting such as Asp.net ConnectionString you need to add the attribute HostType to your method, else they wont load even if you have an App.Config file.

[TestMethod]
[HostType("ASP.NET")] // will load the ConnectionString from the App.Config file
public void Test() {

}

I use NUnit and in my project directory I have a copy of my App.Config that I change some configuration (example I redirect to a test database...). You need to have it in the same directory of the tested project and you will be fine.


nUnit 2.5.10에서 작동하는 이러한 제안을 얻을 수 없으므로 nUnit의 Project-> Edit 기능을 사용하여 대상 구성 파일을 지정하는 것으로 끝났습니다 (다른 사람들이와 동일한 폴더에 있어야한다고 말했듯이). nunit 파일 자체). 이것의 긍정적 인 측면은 구성 파일에 Test.config 이름을 부여하여 그것이 무엇인지와 그 이유를 훨씬 명확하게 할 수 있다는 것입니다)

참고 URL : https://stackoverflow.com/questions/344069/can-a-unit-test-project-load-the-target-applications-app-config-file

반응형