Clear Filters
Clear Filters

Programmatically close App Designer app after running it for a unit test

6 views (last 30 days)
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.

Accepted Answer

Adam Danz
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)
  • 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
  7 Comments
Steven Lord
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
Here is where I'd close the figure.
Arrays have incompatible sizes for this operation.
Adam Danz
Adam Danz on 16 May 2024
Thanks for pointing out my mistake @Steven Lord.
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.

Sign in to comment.

More Answers (0)

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!