Executing function inside script-based unit test?

1 view (last 30 days)
I am trying to write Unit Tests using this method.
I have a file, say "GAS_ENGINE.m" that (simplified) goes like this
function GAS_ENGINE
if (METRIC)
if temp > this && that
%do stuff
elseif temp > this2
%do other stuff
else
%do other stuff
else
%same as above, non metric numbers
end
end
I have another file, GAS_ENGINE_TEST.m where I am trying to execute some simple unit tests. IE are the proper flags raised if the temp is outside of a certain range?
How can I execute GAS_ENGINE.m and have it run through necessary lines of code, from inside GAS_ENGINE_TEST.m?

Answers (2)

Steven Lord
Steven Lord on 15 Sep 2017
When you simplified the function, did you simplify away the inputs and outputs? While it is often possible to test functions that accept no inputs (depending on reading files, querying properties of objects in a GUI, etc. to control its behavior) and return no outputs but some change to the environment (creating a figure, writing a file, etc.) IMO it's easier if you can control the behavior via input arguments and validate the output arguments directly.
As an example, if the function you're testing must not accept inputs but instead be controlled via files that it reads in, you could still test it. Using the four phase test terminology, creating the control files corresponding to the behavior you want to test would be your Setup. Running the function you're testing would be Exercise. Checking that the artifacts created by the function match your expectations is Verify. Deleting the files that you created during Setup would be your Teardown, restoring the system (the function + the space on disk where the function looks for its control files) to its original state.
If you were able to provide a few more details, such as a less simplified version of your function, we may be able to offer more specific suggestions.

Andy Campbell
Andy Campbell on 15 Sep 2017
Hi Nick,
I might be missing something here, but you just execute the function from within your script based test. Does your function return outputs are accept inputs? I think this standard way to test would be to drive the function with certain inputs and confirm that the right outputs are produced. If the function instead doesn't have inputs and outputs, but looks at the environment for its inputs (for example if it checks some globally accessible METRIC) and then has some side effect as a result, then you need to set the environment up properly beforehand before you call the function and then check that right right side effect occurred. Generally, if possible I would encourage the former approach, since dealing with global state and side effects can be very difficult to manage.
Hope that helps!

Categories

Find more on Testing Frameworks in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!