unit-testingbatch-fileautomated-tests

Is there a unit-test framework for Windows batch files?


I need just something very simple like "run this command and succeed if there is 'this string' somewhere in the console output, fail otherwise". Is there such a tool?


Solution

  • Not that I'm aware of, but you can easily write one in another batch script.

    call TestBatchScript.cmd > console_output.txt
    findstr /C:"this string" console_output.txt
    

    will set %errorlevel% to zero if the string is found, and nonzero if the string is absent. You can then test that with IF ERRORLEVEL 1 goto :fail and execute whatever code you want after the :fail label.

    If you want compact evaluation of several such strings, you can use the || syntax:

    call TestBatchScript.cmd > console_output.txt
    findstr /C:"teststring1" console_output.txt || goto :fail
    findstr /C:"teststring2" console_output.txt || goto :fail
    findstr /C:"teststring3" console_output.txt || goto :fail
    findstr /C:"teststring4" console_output.txt || goto :fail
    goto :eof
    
    :fail
    echo You Suck!
    goto :eof
    

    Or, you can go even further and read the list of strings from a file

    call TestBatchScript.cmd > console_output.txt
    set success=1
    for /f "tokens=*" %%a in (teststrings.txt) do findstr /C:"%%a" console_output.txt || call :fail %%a
    if %success% NEQ 1 echo You Suck!
    goto :eof
    
    :fail
    echo Didn't find string "%*"
    set success=0
    goto :eof