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

8 次查看(过去 30 天)
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.

采纳的回答

Adam Danz
Adam Danz 2024-5-16
编辑:Adam Danz 2024-5-16
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 个评论
Steven Lord
Steven Lord 2024-5-16
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 2024-5-16
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Script-Based Unit Tests 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by