Is there a way to display a message when a unit test passes. Such as what it was testing.
I know I can show a message when it fails to pass
function testOne (testCase)
% some test here
msg = 'This will show what it fails';
testCase.assertEqual(properties(Object), expProp, msg);
end
Expanding on kyamagu's comment, assuming you are using R2014a you can write a listener that listens to AssertionPassed events. This listener is a function that take the source object (the TestCase instance) and an event data instance which contains information about the assertion like the actual value, the constraint used, and diagnsotics passed by the user. If you are doing this for one test you can jsut add this listener directly inside the test
methods(Test)
function testOne (testCase)
testCase.addlistener('AssertionPassed', ...
#(src,evd) disp('This will show what it succeeds'));
% some test here
msg = 'This will show what it fails';
testCase.assertEqual(properties(Object), expProp, msg);
end
end
If you want to show something about the success for every single assertion or verification, you may be able to get what you want by writing your own plugin. Plugins get handed the correct TestCase instances and can use them to add these listeners for both passing and failing qualifications. Once you write a plugin, you can install it onto a TestRunner and be able to get the desired behavior for all assertions, verifications, etc.
What about helpdlg?
function testOne (testCase)
% some test here, result is boolean in variable Test
if Test
msg = 'This will show what it succeeds';
helpdlg(msg);
else
msg = 'This will show what it fails';
testCase.assertEqual(properties(Object), expProp, msg);
end
end
You could add a timer for it to disappear after a certain amount of time... Also disp is a solution if it's for inline commands...
Related
I am trying to handle exceptions gracefully such that when a user enters a character, when a number is expected, he is notified with a custom warning/message.
I know that the try, catch has the following syntax:
try
statements
catch exception
statements
end
I have been trying something like this, to no avail:
number = input('Enter number');
try
assert(isnumeric(number));
catch ME
warning('NOT A NUMBER');
end
I do not understand why the above code fails since assert if it is false, displays the error message 'Assertion Failed'.
I know that using try and catch is a bit of a sledgehammer approach, but I would like to understand how to implement the above functionality. Any tips would be appreciated.
From the help command:
input Prompt for user input.
RESULT = input(PROMPT) displays the PROMPT string on the screen, waits
for input from the keyboard, evaluates any expressions in the input,
and returns the value in RESULT. To evaluate expressions, input accesses
variables in the current workspace. If you press the return key without
entering anything, input returns an empty matrix.
Therefore if a user types in "goat" MATLAB will try to evaluate the variable named "goat". That is not helpful for this problem.
However looking further down the help command:
STR = input(PROMPT,'s') returns the entered text as a MATLAB string,
without evaluating expressions.
This is what is more applicable to your problem.
number = input('Enter number', 's');
try
assert(~isnan(str2double(number)));
catch ME
warning('NOT A NUMBER');
end
I have a matlab script, where I would like to dynamically create sections in my matlab publish.
At present, the only way I know to create a section break, is to put code like this in my script:
%% This is a section break
I'd like to run publish on my script, and have the section breaks get added as part of the publish. For instance. Say I had the following script:
breaks(1).name = 'This is section break 1.';
breaks(2).name = 'This is section break 2.';
for ix = 1 : numel(breaks)
functionThatInsertsSectionBreakTitle(breaks(ix).name);
fprintf('Some random processing associated with break %d.\n', ix);
end
I would like to call publish on that script, and end up with a document that looks something like:
This is section break 1.
Some random processing associated with break 1.
This is section break 2.
Some random processing associated with break 2.
Obviously I could do this by writing a script that writes a script that then gets executed by publish. I was hoping for something a bit more direct. Am aware of the report generation toolbox, which I would hope would cleanly handle this type of scenario. Alternatively, if the new (as of R2016a) Live Script handles this use case, that's a fine answer as well.
One way to address this problem is by displaying html code in the command output (documented here).
In your example, the code would look like this:
breaks(1).name = 'This is section break 1.';
breaks(2).name = 'This is section break 2.';
for ix = 1 : numel(breaks)
disp(['<html><h2>' breaks(ix).name '</h2></html>']);
fprintf('Some random processing associated with break %d.\n', ix);
end
This is incredibly useful when you want to get results to be displayed with a custom layout, such as a table. And it avoids the need of having a Matlab Report Generator license...
I'm looking to both catch and handle the "unassignedOuputs" error in Matlab. More specifically, looking at the following code:
try
[out1,out2]= somefunction(in1,in2);
catch err
if strcmp(err.identifier,'MATLAB:unassignedOutputs')
<some code>
else
rethrow(err);
end
end
If "somefunction" does not assign out2 and the resulting error is caught, is it possible to somehow retrieve the rest of the outputs from the function (in this case out1)? If not, is there a way to re-call the function ignoring that value so the function will not throw the error?
As far as I can tell, there is no way to retrieve variables once the function has been terminated with this error. For the case when the first output is produced but not the second, you could retry it with just one output, naively something like:
try
[out1,out2]= somefunction(in1,in2);
catch err
if strcmp(err.identifier,'MATLAB:unassignedOutputs')
try
out2 = [];
out1 = somefunction(in1, in2);
catch err2
% rethrow original error
rethrow(err)
end
else
rethrow(err);
end
end
To display a message saying which output wasn't assigned, you'd have to parse err.message (although the default message itself should be reasonably clear).
But getting this to work if you have more than two outputs, and you don't know which might have not been properly defined, would not be simple. And if the first output is not defined, this won't work at all. In that case you would have to, I think, edit the function itself.
If the specific use case is checking a bunch of student codes which all take the same inputs and provide the same outputs, an alternative option would be to provide them with a function template which contains a check at the end if the outputs exist, and if not sets them to empty and displays your custom message.
I have created a GUI in matlab with a edit box and the user should enter a function so the program may evaluate some values.
However how do I retrieve the function in the textbox and how do I make the proper validations for example if the user enters "sin(coserewrwfc(x))"
My code is:
f = get(handles.funcion,'String');
f =inline(f)
f(0)
Thanks for your help
Here's one way of going about it. Basically it's the same as your code, but in a try/catch block so that if there is an error trying to do f(0), the code will keep running. It will enter the catch statement, where you can manage the error, maybe by displaying a message box asking for the function to be entered again.
try
f = inline(get(handles.funcion,'String'));
f(0); %// try something that would fail if the function is defined incorrectly
catch
disp('There was a problem, please try again')
end
How can I see the error messages of assumeThat in JUnit4?
This test passes but does not print anything. The reason is that to perform the test on read1, I require b to be true. Since b is false, the test does not apply.
boolean b = false;
byte[] read1 = null;
assumeThat("b shold be true to continue testing", b, is(true));
assertThat("read1 should not be null", read1, is(notNullValue()));
I have not found any kind of log with the assumeThat messages. My issue here is that I would like to know which tests passed but did not completed because assumption X failed. It would be nice if a message (for example similar to when an assertion fails) was still printed for the assumptions.
Strangely as it may seem, I haven't been able to find comments on this problem (including in the JUnit page). So there is a chance that I'm just doing something wrong or looking for messages in the wrong place. I'm using Eclipe.
If I understand you correctly, the
assertThat("read1 should not be null", read1, is(notNullValue()));
should only be executed if b == true, but it's not an error if b == false?
Then why don't you simply do:
if(b) {
assertThat("read1 should not be null", read1, is(notNullValue()));
} else {
log.warn("b == false, Test on read1 skipped");
}
? Or do you want to have a special test result state ("success-but-suspicious") if that happens?
Update: I just re-read the docs on Assume. It states that if an assumtion fails, the entire test is considered "not meaningful" and marked as "ignored". With small, focused tests that should usually give you all the info you need.
Update2: Just tried it with the JUnit 4.8 in Eclipse 4.2 I have on hand here. That just marks the test as successful. So I guess the JUnit runner in Eclipse might not support that feature correctly.
An error isn't printed because an assumption failure isn't an error. The assume methods are used to short-circuit tests that should not be run due to the value or state one or more objects (or primitives). Assumptions were designed for the Theories runner but they can be used in other runners as well.
One common usage of assumptions is when you have multiple test methods that need to perform some set of operations to get an object into a particular state before the actual test case logic can be performed.
Before assumptions, each test would get the object into a desired state, assert that it is in that state, then continue. For example, for a test of a stack, many tests require a non-empty stack, so you would create a stack, push an item, assert the stack is not empty, then do the rest of the test (pop an item, push another item, etc).
The problem comes if you do this pattern in multiple tests, and then a bug gets introduced that causes all of these tests to fail (for example, isEmpty() always returning true). When you run the tests you get so many failures that you don't know where to start.
So instead you have one test that verifies that if you push an item into an empty stack, isEmpy() returns false. Then any test that needs a non-empty stack does this:
Stack<Object> stack = new Stack<>();
stack.push(new Object());
assumeFalse(stack.isEmpty());
// Continue with the test methods
If you want an error message, you probably want to use an assertion.
Agreeing with the previous answer (by NamshubWriter).
However, if you really want (justifiably) to have a clear indication that the test was ignored because some assumption failed, you can do something like:
#Before
public void before() {
final String mandatoryPropKey = "system.mandatory-property-for-this-test";
final String mandatoryPropExpectedVal = "true";
try { // try/catch because the Assume failure won't print any message (by design)
Assume.assumeTrue("Assumed that the \"" + mandatoryPropKey + "\" system property is \"" + mandatoryPropExpectedVal + "\".", Boolean.valueOf(System.getProperty(mandatoryPropKey, mandatoryPropExpectedVal)));
} catch (AssumptionViolatedException ave) {
logger.warn("Not executing this test because this assumption failed: {}", ave.getMessage());
throw ave;
}
}