필터 지우기
필터 지우기

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

조회 수: 7 (최근 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개)

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by