2015-02-23 71 views
1

我正在嘗試Moq需要2個流的方法。 IE:StreamReader和StreamWriter。但是,當我運行我的測試時,我似乎無法傳遞編譯器正在拋出的異常。每次運行測試時,都會遇到System.IO.IOException,因爲另一個進程正在使用該蒸汽。嘲笑需要兩個流同時打開的服務方法

public void LoadStockLevels(string reportId) 
{ 
    //read file line by line 
    CreateRequiredFiles(reportId); 
    _updateItemList = new List<IStockLevelItem>(); 
    _updateAttributeItemList = new List<AttributeItem>(); 

    try 
    { 
     _sr = _streamReaderWrapper.GetStreamReader(_report + reportId + ".xml"); 
     while ((_line = _sr.ReadLine()) != null) 
     { 
      //sync stock levels 
      var stockItem = _line.Split('\t'); 
      if (stockItem[0] != "sku") 
      { 
       _updateItemList.Add(new StockLevelItem() 
       { 
        Identifier = stockItem[1], 
        Sku = stockItem[0], 
        Quantity = stockItem[3] 
       }); 
       _updateAttributeItemList.Add(new AttributeItem() 
       { 
        AttributeValue = stockItem[1], 
        AttributeKey = "IDENT" 
       }); 
      } 
      else 
      { 
       _wsr = _streamWriterWrapper.GetStreamWriter(_inventoryFile, true); 
       _wsr.WriteLine(
        "sku price minimum-seller-allowed-price maximum-seller-allowed-price quantity leadtime-to-ship"); 
       _wsr.Close(); 
      } 
     } 
     _sr.Close(); 
    } 
    catch (Exception ex) 
    { 
     if(_sr != null) _sr.Close(); 
     if (_wsr != null) _wsr.Close(); 
     _log.Error("Failed to load stock levels", ex); 
    } 
} 

單元測試:

[Test] 
public void Test_LoadStockLevels_CatchesException() 
{ 
    using (var stream1 = new MemoryStream()) 
    { 
     using (var bmp1 = new Bitmap(1, 1)) 
     { 
      var graphics1 = Graphics.FromImage(bmp1); 
      graphics1.FillRectangle(Brushes.Black, 0, 0, 1, 1); 
      bmp1.Save(stream1, ImageFormat.Jpeg); 
     } 
     _streamWriterWrapper.Setup(s => s.GetStreamWriter(It.IsAny<string>(), It.IsAny<bool>())) 
     .Returns(new StreamWriter(stream1.ToString(), true)); 

    } 

    using (var stream2 = new MemoryStream()) 
    { 
     using (var bmp2 = new Bitmap(1, 1)) 
     { 
      var graphics2 = Graphics.FromImage(bmp2); 
      graphics2.FillRectangle(Brushes.Black, 0, 0, 1, 1); 
      bmp2.Save(stream2, ImageFormat.Jpeg); 
     } 
     _streamReaderWrapper.Setup(s => s.GetStreamReader(It.IsAny<string>())) 
      .Returns(new StreamReader(stream2.ToString())); 
     // Assert something with postedFile here 
     _stockSyncService = new StockSyncService(_stockSync.Object, _tService.Object, _features.Object, 
      _macduffClient.Object, _configManager.Object, _streamReaderWrapper.Object, _streamWriterWrapper.Object); 
     var result = _stockSyncService.LoadStockLevels("504978"); 
     Assert.IsInstanceOf<StreamWriter>(result); 
    } 
} 

我知道嘲笑流已經回答了這個問題,但我不知道這個問題已經被問。

是否有可能嘲笑使用2個流與內存流所需的測試。

/**編輯:新增堆棧跟蹤**/

Test 'StockIntergration.Services.Tests.StockSync.StockSyncServiceTests.Test_LoadStockLevels_CatchesException' failed: 
    System.IO.IOException : The process cannot access the file 'C:\Users\ianrichards\Documents\Repositories\StockIntergration\StockIntergration.Services.Tests\bin\Debug\System.IO.MemoryStream' because it is being used by another process. 
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 
    at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost) 
    at System.IO.StreamReader..ctor(String path) 
    StockSync\StockSyncServiceTests.cs(199,0): at StockIntergration.Services.Tests.StockSync.StockSyncServiceTests.Test_LoadStockLevels_CatchesException() 

0 passed, 1 failed, 0 skipped, took 3.71 seconds (NUnit 2.6.2). 
+0

這是什麼'新的StreamWriter應該做的(stream1.ToString(),TRUE))'代碼? – 2015-02-23 15:38:26

+0

請同時添加完整的信息(也有堆棧跟蹤的幾行)。 – 2015-02-23 15:40:42

回答

0

你可以做個試驗,而無需使用。流處理有很大問題。取消使用並手動關閉,並在測試結束時處理流。

0

下面的代碼是罪魁禍首:

 new StreamWriter(stream1.ToString(), true)) 

ToString上大多數類返回類的名字,它到底是什麼例外展示 - new StreamReader("MemoryStream", true)嘗試當前文件夾中創建的文件與給定的名稱和失敗。

您正在尋找在第一個字節數組創建另一個MemoryStream

new StreamWriter(new MemoryStream(stream1.ToArray(), false)));