2013-12-19 70 views
0

我尝试将一些值传递给httpserver。 这是我的班级如何为类创建对象?

public interface ICommandRestClient 
{ 
    IRestResult Send(IMessageEnvelope envelope); 
} 
public class CommandRestClient : ICommandRestClient 
{ 
    private readonly string _serverAddress; 

    /// <summary> 
    /// Use to configure server address 
    /// </summary> 
    /// <param name="serverAddress">Configured serveraddress</param> 
    public CommandRestClient(string serverAddress) 
    { 
     _serverAddress = serverAddress; 
    } 

    public IRestResult Send(IMessageEnvelope envelope) 
    { 
    //do 
    } 
} 

及其工作。现在我试着为Send方法写一些Xunit测试类。为此,我需要创建一个对象来访问CommandRestClient类。但我没有serverAddress值。我想通过强化地址值或不通过serverAddress来为CommandRestClient类创建一个对象。请帮我 谢谢。

+0

做一个适当的值了(单或工厂)为无论你在CommandRestClient执行测试。如果测试*使用* ICommandRestClient,那么你可能会嘲笑(并且完全忘记serverAddress)。 – user2864740

+0

您的主题不反映您的帖子。 – BDR

回答

1

通常,您将创建一个名为CommandRestClientTest的xunit类来测试CommandRestClient。您可以对该类中的ServerAddress常量进行硬编码,以便对serverAddress进行硬编码并将其传递给您在该xunit类中创建的每个CommandRestClient实例。

请记住,如果您实际上正在测试send方法到某个集成测试的位置。要成为一个纯粹的单元测试,你可以模拟外部交互,只测试CommandRestClient中的业务逻辑

在单元中,你通常会把它放在标记为[Setup]的初始化中,但是xunit鼓励你在每个方法中创建对象。

示例代码(没有编译它)

public class CommandRestClientTest 
{ 
    const string testServerAddress = "localhost:8080"; 

    [Fact] 
    public void TestSomeMethod() 
    { 
     CommandRestClient commandRestClient = new CommandRestClient(testServerAddress); 

     //test, assert etc 
    } 
} 
+0

是这样的吗? private readonly CommandRestClient _commandRestClient = new CommandRestClient(“http:// localhost:8088 /”); – user3044294