- use a addTeardown
- use a try/catch block to catch errors in the startup function and close the app when there is an error
- for public functions, call the function directly from the app object within verifyError and then close the app
- If possible (outside of App Designer) reorganize code to move validation before figure creation
Programmatically close App Designer app after running it for a unit test
8 views (last 30 days)
Show older comments
I need to run mlapp myApp for a unit test, but after the test I want the app window to be closed. The only way I know to do this is to search for the app UI Figure in all graphics objects, but I feel there should be a more elegant way.
In my example there is a function appStartup that is called by myApp when the app is started, and appStartup should throw an error if the app can't be run. My code looks like:
function testAppNotRunnable(testCase)
% code here to make sure the app can't run
verifyError(testCase, @() myApp, "appStartup:cantRunApp") % appStartup errors when called by myApp
% close open app windows
h = findall(groot, 'Tag', 'my app tag');
close(h)
This works, but seems inelegant.
0 Comments
Accepted Answer
Adam Danz
on 16 May 2024
Edited: Adam Danz
on 16 May 2024
Original answer removed due to error. See discussion below.
Summary of approaches (thanks to Steven Lord)
7 Comments
Steven Lord
on 16 May 2024
Another possibility could be to wrap the startup code in your appStartup function in a try / catch block. If an error occurs in the try part of the block, close the figure (if it exists) before calling rethrow on the error.
try
x = (1:2) + (1:3);
catch ME
disp("Here is where I'd close the figure.")
rethrow(ME)
end
Adam Danz
on 16 May 2024
If the app subclasses from matlab.apps.AppBase I'm not aware of a way to run one of its methods (e.g. the startup function) before opening/creating the app.
However, once the app object exists, you can independently call any of its public functions. For example, if appStartup is a public function in myApp and the expected error it throws is independent of the initialization at startup, you could verify the error using,
app = myApp;
verifyError(testCase, @() appStartup(app), "appStartup:cantRunApp")
close(app.UIFigure)
But I like Steven's addTeardown idea best and wish I had thought of it.
More Answers (0)
See Also
Categories
Find more on Script-Based Unit Tests in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!