2015-12-03 86 views
2

我想弄清楚爲什麼我的單元測試在與解決方案中的其他單元測試一起運行時會失敗,但在單獨運行時通過。任何人都可以告訴我我錯過了什麼?測試異步方法不會給出一致的結果

SUT是一個名爲CompositeClient的類,它本質上是一個圍繞其他兩個客戶端的包裝類。主要想法是優先考慮其中一個被調用的客戶。

public class CompositeClient : IReceiverChannel 
{ 
    private static readonly List<IReceiverChannel> ReceiverChannels = new List<IReceiverChannel>(); 

    public CompositeClient(IReceiverChannel priority, IReceiverChannel normal) 
    { 
     ReceiverChannels.Add(priority); 
     ReceiverChannels.Add(normal); 
    } 

    public async Task<IEnumerable<Request>> ReceiveBatchAsync(int batchSize) 
    { 
     var req = new List<Request>(); 

     foreach (var channel in ReceiverChannels) 
     { 
      req.AddRange(await channel.ReceiveBatchAsync(batchSize - req.Count).ConfigureAwait(false)); 

      if (req.Count >= batchSize) 
      { 
       break; 
      } 
     } 

     return req; 
    } 
} 

運行下面的單元測試以及解決方案中的所有其他單元測試都會導致失敗的結果。但是如果我單獨運行這個測試,它會通過。

[TestMethod] 
public async Task ReceivedRequestShouldComeFromPriorityClientFirst() 
{ 
    var normalPriorityClient = GetNormalClientMock(); 
    var highPriorityClient = GetPriorityClientMock(); 
    var compositeClient = new CompositeClient(highPriorityClient, normalPriorityClient); 

    var requests = await compositeClient.ReceiveBatchAsync(1); 

    requests.Should().HaveCount(1); 
    requests.First().Origin.Should().BeSameAs("priority"); 

    normalPriorityClient.CallCount.Should().Be(1); // It will fail here with actual CallCount = 0. 
    highPriorityClient.CallCount.Should().Be(0); 
} 

private static ReceiverChannelMock GetNormalClientMock() 
{ 
    return new ReceiverChannelMock("normal"); 
} 

private static ReceiverChannelMock GetPriorityClientMock() 
{ 
    return new ReceiverChannelMock("priority"); 
} 

private class ReceiverChannelMock : IReceiverChannel 
{ 
    private readonly string name; 

    public ReceiverChannelMock(string name) 
    { 
     this.name = name; 
    } 

    public int CallCount { get; private set; } 

    public Task<IEnumerable<Request>> ReceiveBatchAsync(int batchSize) 
    { 
     this.CallCount++; 
     return Task.FromResult<IEnumerable<Request>>(
      new List<Request> 
          { 
           new Request 
            { 
             Origin = this.name 
            } 
          }); 
    } 
} 

所使用的工具:

  • 的Visual Studio 2013
  • 的.NET Framework 4.5.2
  • ReSharper的9.2
  • FluentAssertion
+3

該類有一個'static'屬性。其他測試是否修改該屬性? 「靜態」成員對單元測試來說很不好。 – David

+0

嗨 - 你指的是哪個靜態屬性? –

+0

'ReceiverChannels' - 聲明中帶有'static'關鍵字的那個。 – David

回答

1

正如David指出,我忽略我在CompositeClient類中聲明的靜態字段。刪除靜態關鍵字解決了問題。