Test value assignment fails
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
David Chlemdorff
am 28 Okt. 2019
Beantwortet: Gkn Cng
am 20 Feb. 2022
Hello,
I have a class that has some properties defined with
(SetAccess=private)
I want to create a unit test that verifies that assigning a value to these properties will throw an error.
something like:
function testCannotChangeProperties(tc)
conf = ConfigurationFile();
conf.filename = 'woo'; % I want to verify that this throws the error 'MATLAB:class:SetProhibited'. You cannot set the read-only property 'filename' of ConfigurationFile
end
Do i really need to wrap that call inside a function to be able to test it?
function testCannotChangeProperties(tc)
conf = ConfigurationFile();
tc.verifyError(@()conf.setFileName('woo'), 'MATLAB:class:SetProhibited')
end
This is not a solution I can use, because the:
conf.filename = 'woo';
Situation is still not tested.
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 28 Okt. 2019
I have a class that has some properties defined with
(SetAccess=private)
I want to create a unit test that verifies that assigning a value to these properties will throw an error.
Why? The MATLAB object system is not part of your system under test. Trust that MathWorks has done the testing that assigning a value to a class property when not in a context that is allowed to access the property errors.
If you absolutely must do this for whatever reason then yes, you will need to write a function. I recommend a class-related function after the end of the class that either accepts an input from the test method or one that creates a new instance of the class and tries to set that property.
2 Kommentare
Steven Lord
am 28 Okt. 2019
Answering the question "Why the fudge is this a private property?" seems to me to be the job of help text before the properties block, not a test. What would prevent that hypothetical "someone else" from modifying both the code and the test?
If you really wanted to guard against that person modifying the code to move a property from private access to public access there are ways to do that using the meta class functionality, but again that doesn't actually prevent that person from modifying both code and test it just makes it more difficult for them to modify that functionality by forcing them to change both code and test.
Storing the code in a source control system (making it easier to undo undesirable changes) and requiring a code review before checking in the code to the source control system can make it even more difficult for an accidental or malicious change to be added to the code.
Weitere Antworten (1)
Gkn Cng
am 20 Feb. 2022
function testInput(value)
conf.filename = value
end
testCase.verifyError(@() testInput(-10), 'MATLAB:validators:mustBeNonnegative');
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!