0

Первоначально я написал тест к сбою, теперь я рассмотрел вопрос, но когда я пытаюсь запустить мой блок тест снова, я получаю эту ошибкуОшибка службы при запуске моего теста Unit

System.InvalidOperationException : Не удалось найти элемент конечной точки по умолчанию, который ссылается на контракт «InventoryManager.Services.IUserService» в разделе конфигурации клиента ServiceModel. Возможно, это связано с тем, что файл конфигурации не найден для вашего приложения или потому, что элемент-конечный элемент, соответствующий этому контракту, не найден в клиентском элементе.

Я понятия не имею, почему это происходит потому, что я использую ту же конфигурацию, в моей тестовой единицы App.Config, как я сделать, это моя служба библиотеки App.config и названия контракта одинаковы.

Сервис Проект Библиотека App.Config

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 
    </configSections> 
    <system.web> 
    <compilation debug="true" /> 
    </system.web> 
    <!-- When deploying the service library project, the content of the config file must be added to the host's 
    app.config file. System.Configuration does not support config files for libraries. --> 
    <system.serviceModel> 
    <services> 
     <service name="InventoryManager.Services.UserService"> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:3637/Service.svc" /> 
      </baseAddresses> 
     </host> 
     <!-- Service Endpoints --> 
     <!-- Unless fully qualified, address is relative to base address supplied above --> 
     <endpoint address="" binding="basicHttpBinding" contract="InventoryManager.Services.IUserService"> 
      <!-- 
       Upon deployment, the following identity element should be removed or replaced to reflect the 
       identity under which the deployed service runs. If removed, WCF will infer an appropriate identity 
       automatically. 
      --> 
      <identity> 
      <dns value="localhost" /> 
      </identity> 
     </endpoint> 
     <!-- Metadata Endpoints --> 
     <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
     <!-- This endpoint does not use a secure binding and should be secured or removed before deployment --> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior> 
      <!-- To avoid disclosing metadata information, 
      set the value below to false before deployment --> 
      <serviceMetadata httpGetEnabled="True" /> 
      <!-- To receive exception details in faults for debugging purposes, 
      set the value below to true. Set to false before deployment 
      to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="False" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    </system.serviceModel> 
    <connectionStrings> 
    <add name="InventoryManagerEntities" connectionString="metadata=res://*/InventoryManagerModel.csdl|res://*/InventoryManagerModel.ssdl|res://*/InventoryManagerModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=JUNIORLABOLD4A3\SQLEXPRESS;initial catalog=InventoryManager;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 
    <entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
    </entityFramework> 
</configuration> 

Unit Test Project App.config

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 
    </configSections> 
    <system.web> 
    <compilation debug="true" /> 
    </system.web> 
    <!-- When deploying the service library project, the content of the config file must be added to the host's 
    app.config file. System.Configuration does not support config files for libraries. --> 
    <system.serviceModel> 
    <services> 
     <service name="InventoryManager.Services.UserService"> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:3637/Service.svc?wsdl" /> 
      </baseAddresses> 
     </host> 
     <!-- Service Endpoints --> 
     <!-- Unless fully qualified, address is relative to base address supplied above --> 
     <endpoint address="" binding="basicHttpBinding" contract="InventoryManager.Services.IUserService"> 
      <!-- 
       Upon deployment, the following identity element should be removed or replaced to reflect the 
       identity under which the deployed service runs. If removed, WCF will infer an appropriate identity 
       automatically. 
      --> 
      <identity> 
      <dns value="localhost" /> 
      </identity> 
     </endpoint> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior> 
      <!-- To avoid disclosing metadata information, 
      set the value below to false before deployment --> 
      <serviceMetadata httpGetEnabled="True" /> 
      <!-- To receive exception details in faults for debugging purposes, 
      set the value below to true. Set to false before deployment 
      to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="False" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    </system.serviceModel> 
    <connectionStrings> 
    <add name="InventoryManagerEntities" connectionString="metadata=res://*/InventoryManagerModel.csdl|res://*/InventoryManagerModel.ssdl|res://*/InventoryManagerModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=JUNIORLABOLD4A3\SQLEXPRESS;initial catalog=InventoryManager;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 
    <entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
    </entityFramework> 
</configuration> 
+0

'baseAddress' немного отличается, это специально? –

+0

Unittest должен быть независимым от любых внешних ресурсов, таких как базы данных, службы и т. Д. –

+0

Обратите внимание, что у вас есть библиотека WCF ** **. Вам нужно будет скопировать раздел '' из файла app.config библиотеки в web/app.config приложения, которое ** размещает ** службу. Даже шаблон проекта библиотеки включает файл app.config, библиотеки ** не используют его **, они используют web/app.config приложения, использующего библиотеку. – Tim

ответ

0

Приложение конфигурационный файл для модульного тестирования должен иметь <clients> сечение, а не <services> раздел.

Удалить раздел из файла конфигурации модульного тестирования в <services>, и заменить его следующим:

<client> 
    <endpoint address="http://localhost:3637/Service.svc" 
      binding="basicHttpBinding" 
      contract="InventoryManager.Services.IUserService"> 
</client> 

<services> раздел используется для определения услуг для приложения-службы, в то время как секция <client> используется для определения к которой будет подключаться клиент.

+0

Привет, Тим, спасибо, это сработало ... У меня только один вопрос, касающийся одного из комментариев выше. «модульный тест должен быть независим от баз данных и служб» ... имеет ли этот app.config в моем тестовом проекте его зависимость от Сервиса? –

+0

@ifelabolz - Я не уверен, так как я не так разбираюсь в модульном тестировании (мы только начали делать это на работе в этом году). Ваш модульный тест по характеру указания на службу делает его зависимым, но я не знаю, как бы вы нарушили эту зависимость. – Tim

Смежные вопросы