unit-testing - 如何对 Excel VBA 代码进行单元测试

标签 unit-testing excel vsto vba

有人有单元测试 Excel VBA 代码的经验吗?我想尽可能轻松地将单元测试引入到一些旧版 Excel VBA 代码中。我的一个想法是使用 VSTO 从 Excel 工作簿内部调用代码。我想知道其他人是否尝试过此方法来对 Excel 代码进行单元测试,以及他们可能用于单元测试 Excel VBA 的任何其他方法。

我希望获得一些有关任何可用框架的指示和/或有关单元测试 Excel VBA 代码的技巧。

最佳答案

Disclaimer: I own Rubberduck's GitHub repository, and I'm one of the devs involved in the project.

Rubberduck正在积极开发中。虽然它远远不仅仅是一个 VBA 单元测试工具,但它工作得非常好,并且可以让您在几乎没有任何样板的情况下编写 VBA 单元测试:

'@TestModule
Private Assert As New Rubberduck.AssertClass

'@TestMethod
Public Sub TestMethod1()
    Assert.Inconclusive "Test method is not written yet."
End Sub

'@TestMethod
Public Sub AnotherTestMethod()
    Assert.IsTrue False, "Something's wrong?"
End Sub

然后您可以在停靠的工具窗口中导航和运行测试方法,该窗口还为您提供用于快速添加 arrange-act-assert 方法 stub 和 AssertClass 的菜单> 也可以是后期绑定(bind)的,因此您不必担心将 Rubberduck 部署在您的开发环境中以外的其他地方,只是为了保持代码的可编译性。

<小时/>

unit testing wiki page Rubberduck 的 GitHub 存储库上的 几乎解释了有关使用它的所有内容。

<小时/>

最新的 2.1 预发布版本包括“fakes”框架的开始,该框架可用于劫持许多通常会干扰单元测试的标准库调用,方法是将标准库字面上变成“test fakes”可以将其设置为在 Rubberduck 单元测试上下文中执行时按照指定的方式运行,例如 MsgBox 调用:

'@TestMethod
Public Sub TestMethod1()
    On Error GoTo TestFail

    Fakes.MsgBox.Returns 42 ' MsgBox function will return 42

    'here you'd invoke the procedure you want to test
    Debug.Print MsgBox("This MsgBox isn't going to pop up!", vbOkOnly, "Rubberduck") 'prints 42

    With Fakes.MsgBox.Verify ' Test will pass if MsgBox was invoked as specified
        .Parameter "prompt", "This MsgBox isn't going to pop up!"
        .Parameter "buttons", vbOkOnly
        .Parameter "title", "Rubberduck"
    End With
TestExit: 
    Exit Sub
TestFail: 
    Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
End Sub

我们非常欢迎您为扩展 Fakes API 以涵盖更多功能做出贡献。覆盖 FileSystemObject 调用将特别有用。

关于unit-testing - 如何对 Excel VBA 代码进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4547487/

相关文章:

excel - 从代码调用Excel宏记录器

ms-word - 将图像添加到 Word 文档,就像拖放一样

javascript - 空注入(inject)器错误 : StaticInjectorError(DynamicTestModule) When Testing in Angular 2

javascript - 测试使用 setInterval 或 setTimeout 的 Angular2 组件

VBA-将每个工作表保存为Excel工作簿中的值

c# - 从 Office 本身更新 ClickOnce VSTO 加载项不会更新加载项

python - 如何正确构建 SQLAlchemy(声明式)python 项目及其单元测试

unit-testing - "Standard"测试过程

excel - 意外的手动分页行为。为什么excel会在错误的行上添加额外的分页符/分页符?

c# - ReportViewer - 如何呈现超过 65,000 行的 Excel 文件?