2010-08-06 90 views
5

Tôi phải viết một bài kiểm tra đơn vị cho phương pháp này nhưng tôi không thể xây dựng HttpPostedFileBase ... Khi tôi chạy phương pháp từ trình duyệt, nó hoạt động tốt nhưng tôi thực sự cần một thử nghiệm đơn vị tự động cho điều đó. Vì vậy, câu hỏi của tôi là: làm thế nào để xây dựng HttpPosterFileBase để truyền một tập tin đến HttpPostedFileBase.Làm thế nào để xây dựng HttpPostedFileBase?

Cảm ơn.

public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files) 
    { 
     foreach (var file in files) 
     { 
      // ... 
     } 
    } 

Trả lời

6

Làm thế nào về làm một cái gì đó như thế này:

public class MockHttpPostedFileBase : HttpPostedFileBase 
{ 
    public MockHttpPostedFileBase() 
    { 

    } 
} 

sau đó bạn có thể tạo một hình mới:

MockHttpPostedFileBase mockFile = new MockHttpPostedFileBase(); 
2

Trong trường hợp của tôi, tôi sử dụng lõi đăng lõi qua asp.net MVC giao diện web và thông qua webservice RPC và thông qua unittest. Trong trường hợp này, việc xác định trình bao bọc tùy chỉnh hữu ích cho HttpPostedFileBase:

public class HttpPostedFileStreamWrapper : HttpPostedFileBase 
{ 
    string _contentType; 
    string _filename; 
    Stream _inputStream; 

    public HttpPostedFileStreamWrapper(Stream inputStream, string contentType = null, string filename = null) 
    { 
     _inputStream = inputStream; 
     _contentType = contentType; 
     _filename = filename; 
    } 

    public override int ContentLength { get { return (int)_inputStream.Length; } } 

    public override string ContentType { get { return _contentType; } } 

    /// <summary> 
    /// Summary: 
    ///  Gets the fully qualified name of the file on the client. 
    /// Returns: 
    ///  The name of the file on the client, which includes the directory path. 
    /// </summary>  
    public override string FileName { get { return _filename; } } 

    public override Stream InputStream { get { return _inputStream; } } 


    public override void SaveAs(string filename) 
    { 
     using (var stream = File.OpenWrite(filename)) 
     { 
      InputStream.CopyTo(stream); 
     } 
    } 
Các vấn đề liên quan