是否有可能在MVC4中对BundleConfig进行单元测试?

时间:2012-07-07 02:03:50

标签: unit-testing asp.net-mvc-4 asp.net-optimization bundling-and-minification

据我所知,答案是否定的。我看到的问题来自Include(params string[])类中的System.Web.Optimization.Bundle方法。在内部,它调用System.Web.Optimization.IncludeDirectory(string, string, bool),后者又使用此代码:

DirectoryInfo directoryInfo = new DirectoryInfo(
    HttpContext.Current.Server.MapPath(directoryVirtualPath));

虽然可以在单元测试期间设置HttpContext.Current,但我无法弄清楚如何使其.Server.MapPath(string directoryVirtualPath)返回非空字符串。由于DirectoryInfo(string)构造函数在传递null参数时抛出异常,因此这样的测试将始终失败。

.NET团队对此有何建议?我们是否必须将捆绑配置作为集成测试或用户验收测试的一部分进行单元测试?

2 个答案:

答案 0 :(得分:9)

我有一些好消息,对于RTM,我们在BundleTable添加了一个新的静态属性以启用更多单元测试:

public static Func<string, string> MapPathMethod;

编辑已更新测试虚拟路径提供程序:

所以你可以这样做:

public class TestVirtualPathProvider : VirtualPathProvider {

    private string NormalizeVirtualPath(string virtualPath, bool isDirectory = false) {
        if (!virtualPath.StartsWith("~")) {
            virtualPath = "~" + virtualPath;
        }
        virtualPath = virtualPath.Replace('\\', '/');
        // Normalize directories to always have an ending "/"
        if (isDirectory && !virtualPath.EndsWith("/")) {
            return virtualPath + "/";
        }
        return virtualPath;
    }

    // Files on disk (virtualPath -> file)
    private Dictionary<string, VirtualFile> _fileMap = new Dictionary<string, VirtualFile>();
    private Dictionary<string, VirtualFile> FileMap {
        get { return _fileMap; }
    }

    public void AddFile(VirtualFile file) {
        FileMap[NormalizeVirtualPath(file.VirtualPath)] = file;
    }

    private Dictionary<string, VirtualDirectory> _directoryMap = new Dictionary<string, VirtualDirectory>();
    private Dictionary<string, VirtualDirectory> DirectoryMap {
        get { return _directoryMap; }
    }

    public void AddDirectory(VirtualDirectory dir) {
        DirectoryMap[NormalizeVirtualPath(dir.VirtualPath, isDirectory: true)] = dir;
    }

    public override bool FileExists(string virtualPath) {
        return FileMap.ContainsKey(NormalizeVirtualPath(virtualPath));
    }

    public override bool DirectoryExists(string virtualDir) {
        return DirectoryMap.ContainsKey(NormalizeVirtualPath(virtualDir, isDirectory: true));
    }

    public override VirtualFile GetFile(string virtualPath) {
        return FileMap[NormalizeVirtualPath(virtualPath)];
    }

    public override VirtualDirectory GetDirectory(string virtualDir) {
        return DirectoryMap[NormalizeVirtualPath(virtualDir, isDirectory: true)];
    }

    internal class TestVirtualFile : VirtualFile {
        public TestVirtualFile(string virtualPath, string contents)
            : base(virtualPath) {
            Contents = contents;
        }

        public string Contents { get; set; }

        public override Stream Open() {
            return new MemoryStream(UTF8Encoding.Default.GetBytes(Contents));
        }
    }

    internal class TestVirtualDirectory : VirtualDirectory {
        public TestVirtualDirectory(string virtualPath)
            : base(virtualPath) {
        }

        public List<VirtualFile> _directoryFiles = new List<VirtualFile>();
        public List<VirtualFile> DirectoryFiles {
            get {
                return _directoryFiles;
            }
        }

        public List<VirtualDirectory> _subDirs = new List<VirtualDirectory>();
        public List<VirtualDirectory> SubDirectories {
            get {
                return _subDirs;
            }
        }

        public override IEnumerable Files {
            get {
                return DirectoryFiles;
            }
        }

        public override IEnumerable Children {
            get { throw new NotImplementedException(); }
        }

        public override IEnumerable Directories {
            get { 
                return SubDirectories;
            }
        }
    }

然后使用它来编写单元测试:

    [TestMethod]
    public void StyleBundleCustomVPPIncludeVersionSelectsTest() {
        //Setup the vpp to contain the files/directories
        TestVirtualPathProvider vpp = new TestVirtualPathProvider();
        var directory = new TestVirtualPathProvider.TestVirtualDirectory("/dir/");
        directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style1.0.css", "correct"));
        directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style.css", "wrong"));
        vpp.AddDirectory(directory);

        // Setup the bundle
        ScriptBundle bundle = new ScriptBundle("~/bundles/test");
        bundle.Items.VirtualPathProvider = vpp;
        bundle.Include("~/dir/style{version}.css");

        // Verify the bundle repsonse
        BundleContext context = SetupContext(bundle, vpp);
        BundleResponse response = bundle.GetBundleResponse(context);
        Assert.AreEqual(@"correct", response.Content);
    }

答案 1 :(得分:6)

在.Net 4.5中,事情略有改变。以下是已更新的已批准答案的工作版本,以适应这些更改(我使用的是Autofac)。注意“GenerateBundleResponse”而不是“GetBundleResponse”:

    [Fact]
    public void StyleBundleIncludesVersion()
    {
        //Setup the vpp to contain the files/directories
        var vpp = new TestVirtualPathProvider();
        var directory = new TestVirtualPathProvider.TestVirtualDirectory("/dir/");
        directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style1.0.css", "correct"));
        directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style.css", "wrong"));
        vpp.AddDirectory(directory);

        // Setup the bundle
        var bundleCollection = new BundleCollection();
        var bundle = new ScriptBundle("~/bundles/test");
        BundleTable.VirtualPathProvider = vpp;
        bundle.Include("~/dir/style{version}.css");
        bundleCollection.Add(bundle);
        var mockHttpContext = new Mock<HttpContextBase>();

        // Verify the bundle repsonse
        var context = new BundleContext(mockHttpContext.Object, bundleCollection, vpp.ToString());
        var response = bundle.GenerateBundleResponse(context);
        Assert.Equal(@"correct", response.Content);
    }