2014-02-25 2 views
1

간단한 단위 테스트를 작성하여 Moq를 배우려고합니다.모의 설정 리더를 설정할 때 오류가 발생했습니다.

public class BackgroundCheckServiceAppSettingsReader : IBackgroundCheckServiceAppSettingsReader 
{ 
    private string _someAppSetting; 

    public BackgroundCheckServiceAppSettingsReader(IWorkHandlerConfigReader configReader) 
    { 
     if (configReader.AppSettingsSection.Settings["SomeAppSetting"] != null) 
      this._someAppSetting = configReader.AppSettingsSection.Settings["SomeAppSetting"].Value; 
    }   

    public string SomeAppSetting 
    { 
     get { return _someAppSetting; } 
    } 
} 

클래스의 인터페이스는 다음과 같이 정의된다 :

public interface IBackgroundCheckServiceAppSettingsReader 
{ 
    string SomeAppSetting { get; } 
} 

그리고 (내가 수정할 수있는 권한이 없습니다)이 IWorkHandlerConfigReader은 그들 중 일부는 클래스라는 AppSettingsReader으로해야 과 같이 정의 : I는 단위 테스트를 작성하는 경우

public interface IWorkHandlerConfigReader 
{ 
    AppSettingsSection AppSettingsSection { get; } 
    ConnectionStringsSection ConnectionStringsSection { get; } 
    ConfigurationSectionCollection Sections { get; } 

    ConfigurationSection GetSection(string sectionName); 
} 

, 내가 IWorkHandlerConfigReaderMock 작성하고 예상되는 B를 설정하려고 ehavior :

//Arrange 
string expectedReturnValue = "This_is_from_the_app_settings"; 
var configReaderMock = new Mock<IWorkHandlerConfigReader>(); 

configReaderMock.Setup(cr => cr.AppSettingsSection.Settings["SomeAppSetting"].Value).Returns(expectedReturnValue); 

//Act 
var reader = new BackgroundCheckServiceAppSettingsReader(configReaderMock.Object); 
var result = reader.SomeAppSetting; 

//Assert 
Assert.Equal(expectedReturnValue, result); 

이 컴파일하지만 내가 테스트를 실행할 때, 나는 다음과 같은 오류를 참조하십시오 System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: cr => cr.AppSettingsSection.Settings["SomeAppSetting"].Value

모의 객체보다이 다른 접근하는 또 다른 방법이 있나요를? 어떻게 사용해야하는지 오해하니?

답변

2

실제로는 AppSettingsSection 인스턴스에 대한 종속성을 묻습니다. 따라서이 속성 getter를 설정하여 필요한 섹션 데이터를 반환하면됩니다.

// Arrange 
string expectedReturnValue = "This_is_from_the_app_settings"; 
var appSettings = new AppSettingsSection(); 
appSettings.Settings.Add("SomeAppSetting", expectedReturnValue); 

var configReaderMock = new Mock<IWorkHandlerConfigReader>(); 
configReaderMock.Setup(cr => cr.AppSettingsSection).Returns(appSettings); 
var reader = new BackgroundCheckServiceAppSettingsReader(configReaderMock.Object); 

// Act 
var result = reader.SomeAppSetting; 

// Assert 
Assert.Equal(expectedReturnValue, result); 
+0

감사합니다. 그래도 여전히 같은 오류가 발생합니다. – Zach

+0

@Zach는 인스턴스를 생성하는 대신'AppSettingsSection'의 모의 객체를 만들려고합니다. –

+0

AppSettingsSection fakeSettingsSection = new AppSettingsSection(); // 그러면 새 인스턴스가 만들어지지 않습니까? – Zach

관련 문제