我有一个服务代理类,可以使Asyn致电服务操作。我使用回调方法将结果传递回我的视图模型。

进行视图模型的功能测试,我可以模拟服务代理以确保在代理上调用方法,但是如何确保调用回调方法?

使用Rhinomocks,我可以测试处理事件并在模拟对象上提出事件,但是如何测试回调?

ViewModel:

public class MyViewModel
{
    public void GetDataAsync()
    {
        // Use DI framework to get the object
        IMyServiceClient myServiceClient = IoC.Resolve<IMyServiceClient>();
        myServiceClient.GetData(GetDataAsyncCallback);
    }

    private void GetDataAsyncCallback(Entity entity, ServiceError error)
    {
        // do something here...
    }

}

ServiceProxy:

public class MyService : ClientBase<IMyService>, IMyServiceClient
{
    // Constructor
    public NertiAdminServiceClient(string endpointConfigurationName, string remoteAddress)
        :
            base(endpointConfigurationName, remoteAddress)
    {
    }

    // IMyServiceClient member.
    public void GetData(Action<Entity, ServiceError> callback)
    {
        Channel.BeginGetData(EndGetData, callback);
    }

    private void EndGetData(IAsyncResult result)
    {
        Action<Entity, ServiceError> callback =
            result.AsyncState as Action<Entity, ServiceError>;

        ServiceError error;
        Entity results = Channel.EndGetData(out error, result);

        if (callback != null)
            callback(results, error);
    }
}

谢谢

有帮助吗?

解决方案

有点玩,我想我可能会想要您想要的东西。首先,我将显示我为验证这一点的MSTST代码:

[TestClass]
public class UnitTest3
{
    private delegate void MakeCallbackDelegate(Action<Entity, ServiceError> callback);

    [TestMethod]
    public void CallbackIntoViewModel()
    {
        var service = MockRepository.GenerateStub<IMyServiceClient>();
        var model = new MyViewModel(service);

        service.Stub(s => s.GetData(null)).Do(
            new MakeCallbackDelegate(c => model.GetDataCallback(new Entity(), new ServiceError())));
        model.GetDataAsync(null);
    }
}

public class MyViewModel
{
    private readonly IMyServiceClient client;

    public MyViewModel(IMyServiceClient client)
    {
        this.client = client;
    }

    public virtual void GetDataAsync(Action<Entity, ServiceError> callback)
    {
        this.client.GetData(callback);
    }

    internal void GetDataCallback(Entity entity, ServiceError serviceError)
    {

    }
}

public interface IMyServiceClient
{
    void GetData(Action<Entity, ServiceError> callback);
}

public class Entity
{
}

public class ServiceError
{
}

您会注意到几件事:

  1. 我将您的回调内部进行。您需要使用internalsvisisbleto()属性,以便您的ViewModel组件将内部设置暴露于您的单元测试(我对此并不疯狂,但是在这种情况下,这种情况发生在这种情况下)。

  2. 我使用犀牛。它没有使用提供的回调,但这实际上是集成测试。我假设您有一个ViewModel单元测试,以确保在适当的时间执行到GetData的真实回调。

  3. 显然,您需要创建模拟/存根实体和ServiceError对象,而不是像我一样新颖。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top