Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9089469
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T22:09:22+00:00 2026-06-16T22:09:22+00:00

In my project I am using: SL5+ MVVM+ Prism + WCF + Rx +

  • 0

In my project I am using: SL5+ MVVM+ Prism + WCF + Rx + Moq + Silverlight Unit Testing Framework.

I am new to unit-testing and have recently started into DI, Patterns (MVVM) etc. Hence the following code has a lot of scope for improvement (please fell free to reject the whole approach I am taking if you think so).

To access my WCF services, I have created a factory class like below (again, it can be flawed, but please have a look):

namespace SomeSolution
{
    public class ServiceClientFactory:IServiceClientFactory
    {
        public CourseServiceClient GetCourseServiceClient()
        {
            var client = new CourseServiceClient();
            client.ChannelFactory.Faulted += (s, e) => client.Abort();
            if(client.State== CommunicationState.Closed){client.InnerChannel.Open();}
            return client;
        }

        public ConfigServiceClient GetConfigServiceClient()
        {
            var client = new ConfigServiceClient();
            client.ChannelFactory.Faulted += (s, e) => client.Abort();
            if (client.State == CommunicationState.Closed) { client.InnerChannel.Open(); }
            return client;
        }

        public ContactServiceClient GetContactServiceClient()
        {
            var client = new ContactServiceClient();
            client.ChannelFactory.Faulted += (s, e) => client.Abort();
            if (client.State == CommunicationState.Closed) { client.InnerChannel.Open(); }
            return client;
        }
    }
}

It implements a simple interface as below:

public interface IServiceClientFactory
{
    CourseServiceClient GetCourseServiceClient();
    ConfigServiceClient GetConfigServiceClient();
    ContactServiceClient GetContactServiceClient();
}

In my VMs I am doing DI of the above class and using Rx to call WCF as below:

var client = _serviceClientFactory.GetContactServiceClient();
try
{

    IObservable<IEvent<GetContactByIdCompletedEventArgs>> observable =
        Observable.FromEvent<GetContactByIdCompletedEventArgs>(client, "GetContactByIdCompleted").Take(1);

    observable.Subscribe(
        e =>
            {
                if (e.EventArgs.Error == null)
                {                                    
                    //some code here that needs to be unit-tested

                }
            },
        ex =>
        {
            _errorLogger.ProcessError(GetType().Name, MethodBase.GetCurrentMethod().Name, ErrorSource.Observable, "", -1, ex);
        }
        );
    client.GetContactByIdAsync(contactid, UserInformation.SecurityToken);
}
catch (Exception ex)
{
    _errorLogger.ProcessError(GetType().Name, MethodBase.GetCurrentMethod().Name, ErrorSource.Code, "", -1, ex);
}

Now I want to build unit tests (yes, its not TDD). But I don’t understand where to start. With Moq I can’t mock the BlahServiceClient. Also no svcutil generated interface can help because async methods are not part of the auto-generated IBlahService interface. I may prefer to extend (through partial classes etc) any of the auto generated classes, but I would hate to opt for manually building all the code that svcutil can generate (frankly considering time and budget).

Can someone please help? Any pointer in the right direction would help me a lot.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T22:09:23+00:00Added an answer on June 16, 2026 at 10:09 pm

    When mocking your service client you are actually mocking one of the interfaces it implements. So in your case it may be IContactService.

    The generated code implements both System.ServiceModel.ClientBase<IContactService> and IContactService. Your dependency provider (in your case a factory) is returning ContactServiceClient – change this to IContactService for starters. This will aid your DI now and in the future.

    Ok, you’re already have an abstract factory and now they return your service interface IContactService. You’re using interfaces only now so the mocking is quite trivial.

    First some assumptions about the code you’re trying to exercise. The code snippet provided messages both the abstract factory and the service client. Provided that the //some code here that needs to be unit-tested section is not going to interact with any other dependencies then you’re looking to mock out both the factory and the service client so that you test is isolated to just the method body code.

    I’ve made an adjustment for the sake of example. Your interfaces:

    public class Contact {
        public string Name { get; set; }
    }
    
    public interface IContactService {
        Contact GetContactById(int contactid);
    }
    
    public interface IContactServiceFactory {
        IContactService GetContactService();
    }
    

    Then your test would look summing like this:

    public void WhateverIsToBeTested_ActuallyDoesWhatItMustDo() {
    
        // Arrange
        var mockContactService = new Mock<IContactService>();
        mockContactService.Setup(cs => cs.GetContactById(It.IsAny<int>()))
            .Returns(new Contact { Name = "Frank Borland" });
    
        var fakeFactory = new Mock<IContactServiceFactory>();
        fakeFactory.Setup(f => f.GetContactService())
            .Returns(mockContactService.Object);
    
        /* i'm assuming here that you're injecting the dependency intoto your factory via the contructor - but 
         * assumptions had to be made as not all the code was provided
         */
        var yourObjectUnderTest = new MysteryClass(fakeFactory.Object);
    
        // Act
        yourObjectUnderTest.yourMysteryMethod();
    
        // Assert
        /* something mysterious, but expected, happened */            
    
    }
    

    EDIT: Mocking the Async Methods

    The async generated methods are not part of your service methods and is created by WCF as part of the Client class. To mock those as an Interface do the following:

    1. Extract the Interface of the ContactServiceClient class. In VS it’s simply a right-click (on the class name), refactor, extract interface. And choose only the applicable methods.

    2. The ContactServiceClient class is partial so create a new class file and redefine the ContactServiceClient class to implement the new IContactServiceClient interface you just extracted.

      public partial class ContactServiceClient : IContactServiceClient {
      }
      

    Like such and now the client class ALSO implements the new interface with the selected async methods. When refreshing your service interface and the service class is re-generated – you don’t have to re-extract the interface as you’ve created a separate partial class with the interface reference.

    1. Create a new factory to return the new interface

      public interface IContactServiceClientFactory {
          IContactServiceClient GetContactServiceClient();
      }
      
    2. Modify the test to work with that interface.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I write a project using Prism . I have tow modules and this modules
I have developed a project using MVC3 and Code first Entity Framework 4.0 as
I am working a project using the AngularJS framework. I am pretty new to
In a web project using jsp, I have following requirement Upload a file (say
i have a JavaScript project (using jquery), inside it i draw a canvas by
I have a lein project (using cascalog--but that's not particularly important). I'm trying to
I have a project using DynamicJasper to create reports. It works fine so far,
Working on a project using Entity Framework (4.3.1.0). I'm trying to figure out how
We have a Silverlight 5 project and we currently have a folder of shared
I have Android project using old OpenGL ES 1. I am using this kind

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.