2013-01-01 31 views
5

在我的几个项目中,我使用MVC模式将代码(关注点)分成3层。 Model和Control层都在C#上运行,所以我使用测试框架(如MSTest或NUnit)来验证这些层的功能需求。对于View层,我使用QUnit来测试JavaScript文件。如何通过JavaScript回调在C#中运行QUnit测试并获取测试结果?

但是,我不能执行QUnit作为自动化测试,因为MSTest不直接支持测试网页。我需要像下面的逻辑一样在MSTest中运行它。

[TestMethod] 
public void JavaScriptTest() 
{ 
    var result = QUnit.Test('~/QUnit/test1.htm'); 

    Assert.IsTrue(result.Failed <= 0) 
} 

解决方案必须使用回调函数在QUnitnot while-loop checking),以确保测试方法测试完成后会立即执行。

回答

5

对于跨浏览器测试,Selenium WebDriver是解决此问题的最佳选择,因为我们可以通过仅更改一行代码轻松切换浏览器。

  1. 安装Selenium WebDriver package通过NuGet进行投影。

enter image description here

2. Download preferred driver到您的项目,添加到项目 ,并设置“复制到输出目录”等于“复制,如果新”。对于这个 示例,我使用Chrome驱动程序在Google机器上运行Selenium并在 我的机器上运行。

enter image description here

3.In测试方法,运行QUnit之前创建驱动程序并设置最大执行时间。

var browser = new ChromeDriver(); 
var navigator = browser.Navigate(); 

// Currently, max execution time is one minute. 
browser.Manage().Timeouts() 
     .SetScriptTimeout(new TimeSpan(0, 1, 0)); 

4.请确定您已经将QUnit的自动启动设置为false。

QUnit.config.autostart = false; 

5.导航到QUnit页面。在这种情况下,我在解决方案文件夹中使用本地网页。在浏览器对象

browser.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 1, 0)); 
navigator.GoToUrl(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../QUnit example/qunit-demo.htm")); 

6.使用ExecuteAsyncScript方法注册回调函数QUnit.done和手动启动QUnit测试。

var response = browser.ExecuteAsyncScript 
(
    "var callback = arguments[arguments.length - 1];" + 
    "QUnit.done(callback); QUnit.start();" 
); 

7.当QUnit测试完成时,它会返回一个响应。我们需要将它转换为合适的类型并获得测试结果。

var testResult = response as Dictionary<string, object>; 

if(testResult == null) throw new Exception("Unhandle error occur while running QUnit."); 

Console.WriteLine("Test complete in " + (long)testResult["runtime"] + " ms."); 
Console.WriteLine("---------------------------"); 
Console.WriteLine("total: " + (long)testResult["total"]); 
Console.WriteLine("passed: " + (long)testResult["passed"]); 
Console.WriteLine("failed: " + (long)testResult["failed"]); 

8.Don't忘记关闭浏览器每次使用结束测试。

browser.Close(); 

PS。我还为此答案提供了Visual Studio 2012解决方案(源代码)。

Click here to download

更新1

  • BUG修复的某个时候开始QUnit系统寄存器回调函数做测试前。
  • 包含本地QUnit页面。
  • 包含IEDriver下载解决方案。但是,此版本不支持Windows 8上的IE10,但它在IE8上运行良好。
+0

#1限制,无法捕获控制台。通常用于复杂系统的JavaScript日志输出。 –

+0

#2限制,最大执行异步脚本为一分钟。 –

2

PhantomJS无头WebKit的使用JavaScript API。它具有对各种Web标准的快速和本地支持:DOM处理,CSS选择器,JSON,Canvas和SVG。它是完整的Web堆栈,是无头网站测试,屏幕截图,页面自动化和网络监控的最佳解决方案。

enter image description here

我建议你,当你想要测试一些JavaScript库,并且不希望使用测试机器上安装的浏览器使用这个框架。

1.请确保您已经将QUnit的自动启动设置为false。

QUnit.config.autostart = false; 

2. Download PhantomJS executable file为Windows,添加到您的项目,并设置“复制到输出目录”等于“复制,如果新”。

3.创建进程以使用2个参数运行PhantomJS.exe,这两个参数是JavaScript文件和经过测试的页面url。

var scriptPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../PhantomScript/main.js")); 
var pageUrl = "file:///" + Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../QUnitExample/qunit-demo.htm")).Replace('\\', '/'); 

var process = new Process 
{ 
    StartInfo = 
    { 
     UseShellExecute = false, 
     RedirectStandardOutput = true, 
     CreateNoWindow = true, 
     WindowStyle = ProcessWindowStyle.Hidden, 
     FileName = "phantomjs.exe", 
     Arguments = "\"" + scriptPath + "\" \"" + pageUrl + "\"" 
    } 
}; 

4.启动进程并检查此进程的退出代码。

process.Start(); 
process.WaitForExit(); 

Assert.AreEqual(process.ExitCode, 0); 

在JavaScript文件,我用eveluateAsync访问页面的上下文中运行QUnit测试,等到它完成,记录测试的量不合格。

page.evaluateAsync(function() 
{ 
    QUnit.done(function(response) 
    { 
     console.log('!Exit' + response.failed); 
    }); 

    QUnit.start(); 

    // If QUnit finish after 2500 ms, system will exit application with code -1. 
    setTimeout(function() 
    { 
     console.log('!Exit-1'); 
    }, 2500); 
}); 

要处理日志,我使用以下代码以退出代码退出进程。

var exitCodeName = '!Exit'; 
page.onConsoleMessage = function (msg) 
{ 
    if (msg.indexOf(exitCodeName) == 0) 
    { 
     var exitCode = parseInt(msg.substring(exitCodeName.length).trim(), 10); 

     phantom.exit(exitCode || 0); 
    } 
}; 

PS。我还提供完整的源代码(VS2012)到我的SkyDrive。您可以通过以下链接下载它。

PhantomJS Test project

这个项目演示如何在MSTest的运行PhantomJS。

PhantomJS Form project

该项目是在C#Windows窗体中写道PhantomJS包装。我在测试项目中使用它来测试“main.js”和“core.js”文件。

enter image description here