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

本文关键字:单元测试 方法 | 更新日期: 2023-09-27 18:02:43

我正在为这个方法编写单元测试。我试过很多次,但仍然不能为它写任何代码。请建议我如何进行单元测试。我使用c#, nunit框架和rhino mock。

提前感谢。

        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 } };
    }

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

让它只做重要的部分。将任何与您试图处理的操作无关的内容拆分到其他类。把它们放在接口后面,这样就可以在单元测试中模拟它们。通过这种方式,您将注意到在这个类中不必对文件i/o进行任何测试。在下面的课程中,我将函数分解为基本部分,一些文件I/o和检索设置。甚至这些设置也与您要测试的当前方法无关。方法只需要验证,例如,扩展,但它如何做并不重要。

提示:尽量避免使用静态实用程序类。给他们自己的班级。也避免外部组件,如网络通信或文件i/o。

因为我没有很多上下文,它可能无法编译。但我还是会这样写:

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;
    }
}

您可以将此函数视为执行特定工作的多个函数的组合。一个函数是获取目标文件路径,另一个是验证扩展名,另一个是验证大小,另一个是创建缩略图,等等。

目标是将复杂的代码分解成可以独立测试的小函数(单元)。因此,当你把它们放在一起时,你会更有信心你的大函数按预期工作。