我想从以测试驱动的方式在 C# 下使用 Remoting 开始,但我卡住了。
我在该主题上发现的一件事是 article by Marc Clifton ,但他似乎通过从控制台手动启动服务器来运行它。
我尝试在测试夹具中启动服务器(即注册服务类)。 我可能也有错误的接口(interface)用法,但稍后会出现。
我总是收到 channel 已注册的异常(抱歉是德语消息)。 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;
}
}
}
最佳答案
我真的没有办法解决你的问题,但我的建议是,不要以这种方式编写单元测试。看这个post .您真正想在这里测试什么代码。我很确定 Microsoft 已经对 .net 附带的 Remoting 功能进行了大量测试。只需更新实现,就可以在过程中对实现服务接口(interface)的类进行单元测试。如果 .net 框架没有使用静态作为注册位,那么注册您的服务接口(interface)的代码将是可测试的,但是唉。您可以尝试将 IChannel 模拟传递给 ChannelServices.RegisterChannel
并以这种方式以某种方式验证您的注册码,但在我看来,这将是浪费时间。
我只想说,测试应该是达到目的的手段,而不是目标本身。
关于c# - C# 中的测试驱动远程处理 - 我需要单独的服务器 AppDomain 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/349603/