Update: This is now much more streamlined in R2017a with the inclusion of FigureDiagnostic and ScreenshotDiagnostic. Check them out before going too far down this path!
Original Answer
You can do this not only for failing conditions but also for passing conditions with a combination of custom diagnostics and the DiagnosticsValidationPlugin. You can do this quickly using a function handle, but if this is something you find you want to do often for many of your tests, consider creating your own subclass of Diagnostic:
classdef PlotDiagnostic < matlab.unittest.diagnostics.Diagnostic
properties
Title
Actual
Expected
end
methods
function diag = PlotDiagnostic(title, actual, expected)
diag.Title = title;
diag.Actual = actual;
diag.Expected = expected;
end
function diagnose(diag)
diag.DiagnosticResult = sprintf('Generating plot with title "%s"', diag.Title);
f = figure('Title', diag.Title);
ax = axes('Parent', f);
plot(ax, 1:numel(diag.Actual), diag.Actual, 'r', 1:numel(diag.Expected), diag.Expected','b');
end
end
end
Then you can have a test that uses this like so:
classdef FooTest < matlab.unittest.TestCase
methods(Test)
function testFails(testCase)
actual = 1:10;
expected = fliplr(actual);
testCase.verifyEqual(actual, expected, PlotDiagnostic('Title1', actual, expected));
end
function testPasses(testCase)
actual = 1:10;
expected = actual;
testCase.verifyEqual(actual, expected, PlotDiagnostic('Title2', actual, expected));
end
end
end
Now once you have those as test diagnostics you will see them in failure conditions. However, you can also see them in passing conditions using the DiagnosticsValidationPlugin, which evaluates diagnostics even in passing conditions to ensure the diagnostic code is bug free (it would be super lame to not catch diagnostic info from a real failure because there was a bug in the diagnostic code that is typically not exercised). This would look like:
>> import matlab.unittest.*;
>> runner = TestRunner.withNoPlugins;
>> runner.addPlugin(matlab.unittest.plugins.DiagnosticsValidationPlugin);
>> suite = TestSuite.fromClass(?FooTest);
>> runner.run(suite)
Note that as of R2014a you can write your own plugin to listen to these passing diagnostics instead of using the DiagnosticsValidationPlugin. Really in this example we are not using this plugin with the intent to validate that the diagnostics are bug free, so it would be better to write a custom plugin with this specific purpose in mind.
Also, in R2014b you can leverage the log method to hook this up to a different dial. If' you'd like you can call:
testCase.log(Verbosity.Detailed, PlotDiagnostic('Title2', actual, expected));
Then you only see the plots when you are using a LoggingPlugin at the "Detailed" verbosity level, for example.