我希望能够单元测试我的Arduino代码。理想情况下,我可以运行任何测试,而无需将代码上传到Arduino。哪些工具或库可以帮助我做到这一点?

目前正在开发的Arduino模拟器可能很有用,但似乎还没有准备好使用。

Atmel的AVR Studio包含一个芯片模拟器,可能很有用,但我不知道如何将它与Arduino IDE结合使用。


当前回答

保持特定于硬件的代码与其他代码分离或抽象,这样您就可以在任何拥有良好工具和最熟悉的平台上测试和调试更大的“休息”。

Basically, try to build as much of the final code from as many known-to-work building blocks as possible. The remaining hardware-specific work will then be much easier and faster. You may finish it by using existing emulators and/or emulating devices on your own. And then, of course, you'll need to test the real thing somehow. Depending on circumstances, that may or may not be very well automatable (i.e. who or what will press buttons and provide other inputs? who or what will observe and interpret various indicators and outputs?).

其他回答

我在编写Arduino代码时使用Searduino。Searduino是Arduino模拟器和开发环境(Makefiles, C代码…),可以使用您最喜欢的编辑器在C/ c++中轻松破解。您可以导入Arduino草图并在模拟器中运行它们。

Searduino 0.8截图:http://searduino.files.wordpress.com/2014/01/jearduino-0-8.png

Searduino 0.9将发布,并在最后的测试完成后立即录制视频....一两天后。

在模拟器上测试并不是真正的测试,但它确实帮助我找到了许多愚蠢的/逻辑错误(忘记执行pinMode(xx, OUTPUT)等)。

顺便说一句:我是Searduino开发人员之一。

使用带有Arduino库的Proteus VSM来调试代码或测试它。

这是在将代码安装到板上之前的最佳实践,但要确保计时,因为模拟不会在板上运行时实时运行。

在没有Arduino单元测试框架的情况下,我创建了ArduinoUnit。下面是一个简单的Arduino草图,展示了它的使用:

#include <ArduinoUnit.h>

// Create test suite
TestSuite suite;

void setup() {
    Serial.begin(9600);    
}

// Create a test called 'addition' in the test suite
test(addition) {
    assertEquals(3, 1 + 2);
}

void loop() {
    // Run test suite, printing results to the serial port
    suite.run();
}

通过抽象出硬件访问并在测试中模拟它,我在单元测试PIC代码方面取得了相当大的成功。

例如,我用抽象PORTA

#define SetPortA(v) {PORTA = v;}

然后SetPortA可以很容易地模拟,而不需要在PIC版本中添加开销代码。

一旦硬件抽象被测试了一段时间,我很快发现代码通常会从测试平台到PIC,并且第一次就能工作。

更新:

对于单元代码,我使用#include seam,对于测试平台,在c++文件中使用#include单元代码,对于目标代码使用C文件。

作为一个例子,我想复用四个7段显示器,一个端口驱动段和第二个选择显示。显示代码通过SetSegmentData(char)和SetDisplay(char)与显示进行接口。我可以在我的c++测试平台中模拟这些,并检查我是否得到了我期望的数据。对于目标,我使用#define,这样就可以直接赋值,而不需要调用函数

#define SetSegmentData(x) {PORTA = x;}

保持特定于硬件的代码与其他代码分离或抽象,这样您就可以在任何拥有良好工具和最熟悉的平台上测试和调试更大的“休息”。

Basically, try to build as much of the final code from as many known-to-work building blocks as possible. The remaining hardware-specific work will then be much easier and faster. You may finish it by using existing emulators and/or emulating devices on your own. And then, of course, you'll need to test the real thing somehow. Depending on circumstances, that may or may not be very well automatable (i.e. who or what will press buttons and provide other inputs? who or what will observe and interpret various indicators and outputs?).