0

我目前正在尝试了解 WCF 的窍门。测试两个操作的并发执行,使用本ServiceBehavior节时:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple,
                 InstanceContextMode = InstanceContextMode.Single,
                 AddressFilterMode = AddressFilterMode.Prefix)]

我想出了以下XUnit测试:

    [Fact]
    public void LongRunningMethod_Two_Calls_To_LongRunningMethod_Execute_And_Return_Concurrently() // This is achieved by setting in Service.cs: ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)
    {
        var timeout1 = 3000;
        var timeout2 = 1;

        var sw1 = new Stopwatch();
        var sw2 = new Stopwatch();

        var task1 = Task.Run(() =>
        {
            sw1.Start();
            client.LongRunningMethod(timeout1, "Call 1 to client.LongRunningMethod(...) finished.");
            sw1.Stop();
        });
        var task2 = Task.Run(() =>
        {
            sw2.Start();
            client.LongRunningMethod(timeout2, "Call 2 to client.LongRunningMethod(...) finished.");
            sw2.Stop();
        });
        Task.WaitAll(new Task[] { task1, task2 });

        Assert.True(sw2.ElapsedMilliseconds < sw1.ElapsedMilliseconds);
    }

测试类的摘录(带有构造函数和析构函数)是:

public class ImplemenationExplorationTesting : IDisposable
{
    private Service service;
    private Server server;
    private Client client;
    private string constructorArgumentString = "A fixed ctor test value that the service should return.";

    public ImplemenationExplorationTesting()
    {
        service = new Service(constructorArgumentString);
        server = new Server(service);
        server.Open();
        client = new Client();
        client.OpenConnection(server.Uri);
    }

    public void Dispose()
    {
        client.CloseConnection();
        server.Close();
    }

    [Fact]
    public void PingName_SendAndReceiveSimpleMessage_Works()
    {
        var expected = "UserName";
        var actual = client.PingName(expected);
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void StringPassedToTheServiceConstructorIsCorrectlyReturnedByServer()
    {
        var expected = constructorArgumentString;
        var actual = client.GetDefaultString();
        Assert.Equal(expected, actual);
    }
}

单独运行测试时,这可以按预期工作。但是,当我同时运行多个测试时,我遇到了时间问题并且测试失败了。从表面上看,这些测试并不是同时不间断地运行,而是似乎是“时间片”的,最终导致了这些问题。所以问题是:

这种行为是否可以预料,我该如何避免?

4

0 回答 0