Unit-testing WCF: Server Side
Original Method
The following sample shows a method of the server which returns a string containing a list of our favorite sources.
C# [ServiceContract(Namespace = "http://AnyServer")] public interface ISourceListProvider { [OperationContract] string GetSourceList(string source); } public class XMLProvider: ISourceListProvider { public string GetSourceList(string source) { MessageHeaderInfo headerInfo = OperationContext.Current.IncomingMessageHeaders[0]; if (headerInfo.Name != "ID") { throw new ArgumentException("Bad Header Info"); } return "<SourceList><Source value=" + source + "/></SourceList>"; } }
VB
<ServiceContract([Namespace]:="http://AnyServer")>
Public Interface ISourceListProvider
<OperationContract>
Function GetSourceList(source As String) As String
End Interface
Public Class XMLProvider
Implements ISourceListProvider
Public Function GetSourceList(source As String) As String Implements ISourceListProvider.GetSourceList
Dim headerInfo As MessageHeaderInfo = OperationContext.Current.IncomingMessageHeaders(0)
If headerInfo.Name <> "ID" Then
Throw New ArgumentException("Bad Header Info")
End If
Return (Convert.ToString("<SourceList><Source value=") & source) + "/></SourceList>"
End Function
End Class
Typemock Isolator Features Used
• Faking Static Methods
• Faking an Instance
• Modifying methods and properties behavior
Scenario
1. Get a handle for a fake Instance of MessageHeaderInfo.
2. Modify the property MessageHeaderInfo.Name to return "ID".
3. Modify the static method OperationContext.Current.IncomingMessageHeaders[0] to return fakeInfo.
4. Create XMLProvider instance and call the method under test, GetSourceList ,and check if the result is as anticipated.
Code
C# [TestMethod, Isolated] public void GetData_SimulateGoodMessageHeader() { // Arrange // Faking MessageHeaderInfo becuase it's an abstarct class and we can't create an instance of it. MessageHeaderInfo fakeInfo = Isolate.Fake.Instance<MessageHeaderInfo>(); Isolate.WhenCalled(() => fakeInfo.Name).WillReturn("ID"); Isolate.WhenCalled(() => OperationContext.Current.IncomingMessageHeaders[0]).WillReturn(fakeInfo); // Act XMLProvider provider = new XMLProvider(); string result = provider.GetSourceList("MySource"); // Assert Assert.AreEqual(@"<SourceList><Source value=MySource/></SourceList>", result); }
VB
<TestMethod(), Isolated()>
Public Sub GetData_SimulateGoodMessageHeader()
' Arrange
' Faking MessageHeaderInfo becuase it's an abstarct class and we can't create an instance of it.
Dim fakeInfo As MessageHeaderInfo = Isolate.Fake.Instance(Of MessageHeaderInfo)()
Isolate.WhenCalled(Function() fakeInfo.Name).WillReturn("ID")
Isolate.WhenCalled(Function() OperationContext.Current.IncomingMessageHeaders(0)).WillReturn(fakeInfo)
' Act
Dim provider As New XMLProvider()
Dim result As String = provider.GetSourceList("MySource")
' Assert
Assert.AreEqual("<SourceList><Source value=MySource/></SourceList>", result)
End Sub