3

我想以测试驱动的方式开始在 C# 下使用 Remoting,但我卡住了。

我在该主题上发现的一件事是Marc Clifton 的这篇文章,但他似乎通过从控制台手动启动服务器来运行服务器。

我尝试在测试夹具中启动服务器(即注册服务类)。我可能也有接口的使用错误,但稍后会出现。

我总是收到频道已注册的异常(对于德语消息感到抱歉)。System.Runtime.Remoting.RemotingException:Der Channel tcp wurde bereits registriert。

在测试方法中注释掉 ChannelServices.RegisterChannell() 行之后,它发生在调用 Activator.GetObject() 中。

我试图将 StartServer() 放入一个线程中,但这也无济于事。我发现创建一个新的 AppDomain 可能是一种可能的方式,但还没有尝试过。

你能告诉我,如果我的方法本质上是错误的吗?我该如何解决?

using System;
using NUnit.Framework;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace Bla.Tests.Remote
{
    [TestFixture]
    public class VerySimpleProxyTest
    {
        int port = 8082;
        string proxyUri = "MyRemoteProxy";
        string host = "localhost";

        IChannel channel;

        [SetUp]
        public void SetUp()
        {
            StartServer();
        }

        [TearDown]
        public void TearDown()
        {
            StopServer();
        }

        [Test]
        public void UseRemoteService()
        {
            //IChannel clientChannel = new TcpClientChannel();
            //ChannelServices.RegisterChannel(clientChannel, false);
            string uri = String.Format("tcp://{0}:{1}/{2}", host, port, proxyUri);
            IMyTestService remoteService = (IMyTestService)Activator.GetObject(typeof(IMyTestService), uri);

            Assert.IsTrue(remoteService.Ping());
            //ChannelServices.UnregisterChannel(clientChannel);
        }

        private void StartServer()
        {
            channel = new TcpServerChannel(port);
            ChannelServices.RegisterChannel(channel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyTestService), proxyUri, WellKnownObjectMode.Singleton);
        }

        private void StopServer()
        {
            ChannelServices.UnregisterChannel(channel);
        }
    }

    public interface IMyTestService
    {
        bool Ping();
    }

    public class MyTestService : MarshalByRefObject, IMyTestService
    {
        public bool Ping()
        {
            return true;
        }
    }
}
4

2 回答 2

1

我真的没有解决您的问题的方法,但我的建议是,不要以这种方式编写单元测试。看到这个帖子。你真的想在这里测试什么代码。我很确定 Microsoft 已经对 .net 附带的 Remoting 功能进行了大量测试。实现你的 Service 接口的类可以在过程中通过更新实现来进行单元测试。如果 .net 框架不使用静态作为注册位,那么注册服务接口的代码将是可测试的,但是,唉。您可以尝试以某种方式将 IChannel 模拟传递给 ChannelServices.RegisterChannel并验证您的注册码,但在我看来,这将是浪费时间。

我只想指出,测试应该是达到目的的一种手段,而不是其本身的目标。

于 2009-03-17T23:18:19.823 回答
0

我找到了一个很好的方法来做我想做的事,只使用 WCF 而不是 Remoting。

我在不到 5 分钟的时间内将Yair Cohen 的文章中给出的源代码移植到了 NUnit,它开箱即用。

于 2008-12-11T12:51:37.977 回答