简体   繁体   English

如何为这种方法编写单元测试

[英]How to write unit test for this method

I am writing unit test for this method. 我正在为这种方法编写单元测试。 I have tried lot of times but still can not write any code for it. 我已经尝试了很多次但仍然无法为其编写任何代码。 Please suggest me how to unit test it. 请建议我如何进行单元测试。 I am using C# , nunit framework and rhino mock. 我正在使用C#,nunit框架和rhino mock。

Thanks in advance. 提前致谢。

        public FileUploadJsonResult AjaxUploadProfile(int id, string branchName, string filepath, HttpPostedFileBase file)
    {
        // TODO: Add your business logic here and/or save the file
        string statusCode = "1";
        string profilePicture = string.Empty;
        string fileExtension = System.IO.Path.GetExtension(file.FileName.ToLower());
        string fileName = id + "_" + branchName;
        string fileNameWithOriginalExtension = fileName + fileExtension;
        string fileNameWithJPGExtension = fileName + ".jpg";
        string fileServerPath = this.Server.MapPath("~/LO_ProfilePicture/" + fileNameWithJPGExtension);
        string statusMessage = string.Empty;
        if (string.IsNullOrEmpty(fileExtension) || !Utility.isCorrectExtension(fileExtension))
        {
            statusMessage = "Profile picture should be of JPG, BMP, PNG, GIF or JPEG format.";
            return new FileUploadJsonResult { Data = new { message = string.Format(statusMessage, fileNameWithOriginalExtension), filename = string.Empty, profilepic = profilePicture, statusCode = "0" } };
        }
        if (file.ContentLength > PageConstants.PROFILE_PICTURE_FILE_SIZE)
        {
            statusMessage = "Profile picture size should be less than 2MB";
            return new FileUploadJsonResult { Data = new { message = string.Format(statusMessage, fileNameWithOriginalExtension), filename = string.Empty, profilepic = profilePicture, statusCode = "0" } };
        }
        Utility.SaveThumbnailImage(fileServerPath, file.InputStream, PageConstants.BRANCH_PROFILE_PICTURE_FILE_HEIGTH, PageConstants.BRANCH_PROFILE_PICTURE_FILE_WIDTH);
        profilePicture = PageConstants.IMAGE_PATH + "LO_ProfilePicture/" + fileNameWithJPGExtension;
        // Return JSON            
        return new FileUploadJsonResult { Data = new { message = string.Format("Profile Picture is successfully uploaded.", fileNameWithOriginalExtension), filename = fileNameWithJPGExtension, profilepic = profilePicture, statusCode } };
    }

Make it do just the essential part. 让它做到必不可少的部分。 Split anything that has nothing to do with the operation you're trying to handle to other classes. 拆分与您尝试处理其他类的操作无关的任何内容。 Put those behind interfaces, so you can mock these in your unittests. 把它们放在接口后面,这样你就可以在你的单元测试中模拟它们。 This way you'll notice you don't have to test anything with file i/o in this class. 这样你就会注意到你不必在这个类中用文件i / o测试任何东西。 In the class below I split up the function in the essential part, some file i/o and retrieving of settings. 在下面的课程中,我将基本部分中的功能分开,一些文件i / o和检索设置。 Even these settings have nothing to do with the current method you're trying to test. 即使这些设置也与您尝试测试的当前方法无关。 The method just needs verification on, for example, the extension, but it doesn't matter on how it does this. 该方法只需要对例如扩展进行验证,但是如何进行验证并不重要。

Tip: try to avoid static utility classes. 提示:尽量避免使用静态实用程序类。 Give them their own class. 给他们自己的课。 Also avoid external components such as network communication or file i/o. 还要避免使用网络通信或文件i / o等外部组件。

As I don't have a lot of context and it may not compile. 因为我没有很多上下文,它可能无法编译。 But I would go with something like: 但我会选择以下内容:

class Controller {
    public FileUploadJsonResult AjaxUploadProfile(int id, string branchName, string filepath, HttpPostedFileBase file) {
        string fileName = id + "_" + branchName;
        string fileExtension = _fileIO.GetExtensionForFile(file);

        if (!_extensionManager.IsValidExtension(fileExtension)) {
            return CreateAjaxUploadProfileError("Profile picture should be of JPG, BMP, PNG, GIF or JPEG format.");
        }

        if (file.ContentLength > _settingsManager.GetMaximumFileSize()) {
            return CreateAjaxUploadProfileError("Profile picture size should be less than 2MB");
        }

        string fileNameWithJPGExtension = fileName + ".jpg";
        string fileServerPath = _fileIO.GetServerProfilePicture(Server, fileNameWithJPGExtension);
        string fileClientPath = _fileIO.GetClientProfilePicture(fileNameWithJPGExtension);

        var dimensions = _settingsManager.GetThumbnailDimensions();
        _fileIO.SaveThumbnailImage(fileServerPath, file, dimensions.Item1, dimensions.Item2);

        // Return JSON      
        var data = new {
                message = "Profile Picture is successfully uploaded.", 
                filename = fileClientPath,
                profilepic = profilePicture,
                statusCode = "1"
            };
        return new FileUploadJsonResult { Data = data };
    }

    private static CreateAjaxUploadProfileError(string message) {
        var data = new {
                message = message, 
                filename = string.Empty,
                profilepic = string.Empty,
                statusCode = "0"
            };
        return new FileUploadJsonResult { Data = data };
    }
}

class FileIO : IFileIO {
    public string GetExtensionForFile(HttpPostedFileBase file) {
        return System.IO.Path.GetExtension(filePath.FileName.ToLower());
    }

    public string GetServerProfilePicture(T server, string file) {
        return server.MapPath( "~/LO_ProfilePicture/" + file);
    }

    public void SaveThumbnailImage(string path, HttpPostedFileBase file, int height, int width) {
        Utility.SaveThumbnailImage(path, file.InputStream, height, width); // or even inline
    }

    public string GetClientProfilePicture(string fileName) {
        return _settingsManager.GetClientImagePath() + "LO_ProfilePicture/" + fileNameWithJPGExtension;
    }
}

class ExtensionManager : IExtensionManager {
    public bool IsValidExtension(string extension) {
        return Utility.isCorrectExtension(fileExtension); // or even inline
    }
}

class SettingsManager : ISettingsManager {
    public Tuple<int, int> GetThumbnailDimensions() {
        return Tuple.Create<int, int>(PageConstants.BRANCH_PROFILE_PICTURE_FILE_HEIGTH, PageConstants.BRANCH_PROFILE_PICTURE_FILE_WIDTH);
    }

    public int GetMaximumFileSize() {
        return PageConstants.PROFILE_PICTURE_FILE_SIZE;
    }
}

You can look at this function as a combination of multiple functions doing specific work. 您可以将此功能视为执行特定工作的多个功能的组合。 One function is getting target file path, another is validating extension, another is validating size, another creates thumbnail, etc. 一个功能是获取目标文件路径,另一个是验证扩展,另一个是验证大小,另一个是创建缩略图等。

The goal is to breakdown the complex code into small testable functions (units) which you can test independently. 目标是将复杂的代码分解为可以独立测试的小型可测试功能(单元)。 So when you put them together you have better confidence that your big function works as expected. 因此,当您将它们放在一起时,您可以更好地确信您的大功能可以按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM