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

时间:2013-03-07 17:10:49

标签: c# asp.net-mvc-4 nunit rhino-mocks

我正在为这种方法编写单元测试。我已经尝试了很多次但仍然无法为其编写任何代码。请建议我如何进行单元测试。我正在使用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 } };
    }

2 个答案:

答案 0 :(得分:1)

让它成为必不可少的部分。拆分与您尝试处理其他类的操作无关的任何内容。把它们放在接口后面,这样你就可以在你的单元测试中模拟它们。这样你就会注意到你不必在这个类中用文件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;
    }
}

答案 1 :(得分:1)

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

目标是将复杂的代码分解为可以独立测试的小型可测试功能(单元)。所以当你把它们组合在一起时,你就更有信心你的大功能按预期工作了。

相关问题