2010-08-06 4 views
5

मुझे इस विधि के लिए एक यूनिट टेस्ट लिखना है, लेकिन मैं HttpPostedFileBase बनाने में असमर्थ हूं ... जब मैं ब्राउज़र से विधि चलाता हूं, तो यह अच्छी तरह से काम करता है लेकिन मुझे इसके लिए एक ऑटोमेटेड यूनिट परीक्षण की ज़रूरत है। तो मेरा सवाल है: मैं HttpPostedFileBase पर फ़ाइल पास करने के लिए HttpPosterFileBase का निर्माण कैसे करूं।HttpPostedFileBase कैसे बनाएं?

धन्यवाद।

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

उत्तर

6

कैसे कुछ इस तरह करने के बारे में: asp.net MVC के माध्यम से कोर पंजीकरण कोर

MockHttpPostedFileBase mockFile = new MockHttpPostedFileBase(); 
2

मेरे मामले में, मैं का उपयोग करें:

public class MockHttpPostedFileBase : HttpPostedFileBase 
{ 
    public MockHttpPostedFileBase() 
    { 

    } 
} 

तो आप एक नया बना सकते हैं वेब इंटरफेस और आरपीसी webservice के माध्यम से और unittest के माध्यम से। इस मामले में, यह 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); 
     } 
    } 
संबंधित मुद्दे