Why VScode PlatformIO unit test can not use function declare in header file?

Viewed 113

VScode PlatformIO unit test can not use function declare in header file, but use the function definition code is work. It show undefined reference to `wifiInit()' enter image description here Code

#include <unity.h>

#include "wifi/wifi.h"

void test_unit() {
    TEST_ASSERT_EQUAL(EXIT_SUCCESS,wifiInit());
}

void setup() {
    delay(2000);
    UNITY_BEGIN(); 
    RUN_TEST(test_unit);
}

void loop() {}

#include <Arduino.h>
#include <WiFi.h>

#ifndef __wifi_init_h_
#define __wifi_init_h_

#define WIFI_SSID "**"
#define WIFI_PASSWD "***"

int wifiInit();
#endif

#include "wifi/wifi.h"

int wifiInit() {
    // 设置ESP32通过WIFI连接网络
    WiFi.begin(WIFI_SSID, WIFI_PASSWD);
    WiFi.config(WiFi.localIP(), WiFi.gatewayIP(), WiFi.subnetMask(), (uint32_t)0xDF050505, (uint32_t)0x72727272);
    // 打印连接状态
    Serial.println("Connecting");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.print("\nIP address: ");
    Serial.println(WiFi.localIP());
    return EXIT_SUCCESS;
}
}

I coyied the wifiInit() in wifi.cpp to the wifi.h, it worked.

1 Answers

This is because the unit test does not build your source file by default, so at link time the linker can't find the definition (.c) of wifiInit (only the declaration, .h) One way to fix this is to tell PlatformIO to build your source files when it runs unit tests: https://docs.platformio.org/en/latest/projectconf/section_env_test.html#test-build-src

[env:myenv]
platform = ...
test_build_src = yes

Be careful though, depending on your test environment you may not have access to platform-specific headers/libraries! i.e. on a native unit test build you would not be able to #include <Arduino> in your source files.

Related