2012-01-10 19 views
6

Làm thế nào để bạn có được xung quanh WebOperationContext là null trong một phương pháp dịch vụ WCF khi thử nghiệm các phương pháp sử dụng NUnitphương pháp với Nunit nhưng WebOperationContext Testing WCF là null

tôi có một dự án thử nghiệm đơn vị sử dụng NUnit để kiểm tra dữ liệu trả về bởi một WCF Phương pháp:

public class SampleService 
{ 
    public XmlDocument Init() 
    { 
     WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
     return _defaultInitializationXMLfile; 
    } 
} 

sau đó, tôi có một phương pháp thử như sau

[TextFixture] 
public class SampleServiceUnitTest 
{ 
    [Test] 
    public void DefaultInitializationUnitTest 
    { 
     SampleService sampleService = new SampleService(); 
     XMLDocument xmlDoc = sampleService.Init(); 
     XMLNode xmlNode = xmlDoc.SelectSingleNode("defaultNode"); 
     Assert.IsNotNull(xmlNode, "the default XML element does not exist."); 
    } 
} 

Tuy nhiên tôi nhận được một lỗi trong quá trình thử nêu

SampleServiceUnitTest.DefaultInitializationUnitTest: 
System.NullReferenceException : Object reference not set to an instance of an object. 

liên quan đến WebOperationContext trong phương pháp SampleService.

Trả lời

5

Thông thường, bạn sẽ muốn giả lập WebOperationContext theo một cách nào đó. Có một số nội dung được tích hợp vào WCFMock có thể làm điều này cho bạn.

Ngoài ra, bạn có thể sử dụng một số dependency injection để có được những WebOperationContext từ một nơi khác, phá vỡ sự phụ thuộc đó, như:

public class SampleService 
{ 
    private IWebContextResolver _webContext; 

    // constructor gets its dependency, a web context resolver, passed to it. 
    public SampleService(IWebContextResolver webContext) 
    { 
     _webContext = webContext; 
    } 

    public XmlDocument Init() 
    { 
     _webContext.GetCurrent().OutgoingResponse.ContentType = "text/xml"; 
     return _defaultInitializationXMLfile; 
    } 
} 

public class MockWebContextResolver : IWebContextResolver 
{ 
    public WebOperationContext GetCurrent() 
    { 
     return new WebOperationContext(...); // make and return some context here 
    } 
} 

public class ProductionWebContextResolver : IWebContextResolver 
{ 
    public WebOperationContext GetCurrent() 
    { 
     return WebOperationContext.Current; 
    } 
} 

Tất nhiên có những cách khác để thiết lập một chương trình dependency injection, tôi chỉ sử dụng chuyển nó vào constructor dịch vụ trong trường hợp này làm ví dụ.

+1

IWebContextResolver là gì? –

Các vấn đề liên quan