How to implement class based unit tests for functions that return random results

I have to write class based unittests for a function which returns random values. I have ideas on how to do that. For example see the testing methods described in this answer of this stackoverflow question.
I want to know how can we implement this for my function using Matlab's class based (matlab.unittest.TestCase) unit test methods.
Lets call my function which returns the random value as "myRandRetFunc" and it looks like following. How can I implement unit testing for it for things described here or for some other ideas you have in mind.
function rndRetVal = myRandRetFunc(inp1, inp2, inp3)
arg1 = aComplexFunc(inp1, inp2)
arg2 = anotherComplexFunc(inp2, inp3)
rndRetVal = rand(arg1, arg2)
end

 채택된 답변

Steven Lord
Steven Lord 2021년 7월 16일
The four phases of a four phase test are Setup, Exercise, Verify, and Teardown. In this case, you want to Setup the random number generator to a known fixed state before the code that relies upon it is Exercised. Use the rng function to do this.

댓글 수: 3

How should I be implementing this? I tried the following three approaches and the last two are not working. In the first one I am getting the following warning for passing the argument 'testCase': "Argument 'testCase' is unused. Should this method be static?"
methods(TestClassSetup)
function setRandNumber(testCase)
rng(06);
end
end
OR
methods(TestClassSetup)
function setRandNumber(testCase)
testCase.rng(06);
end
end
OR
methods(Static)
function setRandNumber()
rng(06);
end
end
Since you know you're not going to use the input, tell MATLAB that explicitly.
methods(TestClassSetup)
function setRandNumber(~)
rng(06);
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품

릴리스

R2020a

질문:

2021년 7월 15일

댓글:

2021년 7월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by