Featured post
php - suggestions for unit testing exceptions -
consider method might throw exception descriptive text:
if ($somecondition) { throw new \whatever\exception('dilithium exhausted'); }
and elsewhere in method block might throw same exception, different text:
if ($anothercondition) { throw new \whatever\exception('differentialator exploded'); }
while writing unit tests class, create failure cases can verify these 2 exceptions thrown properly. in these failure cases, prefer to:
a) use @exceptionexpected in test method's docblock trap generic \whatever\exception class , subsequently ignore getmessage() text, assuming got right one? (seems bad idea.)
or:
b) use try/catch , assert caught exception's getmessage() text equals exact descriptive string you're expecting? (more resilient means changing tests whenever change error wording.)
or:
c) create separate exception each error case (e.g., \whatever\dilithiumexception , \whatever\differentialatorexception) , use @exceptionexpected each one.
i'm using b tending toward c. i'm curious others doing in same scenario. have guidelines determine, "at point error deserve own exception class versus more generic shared one?"
all of above.
a great, , use as possible because simplest. there case when not work:
/** * @exceptionexpected fooexception */ test() { // code throw fooexception ... // purpose of test throws of fooexception }
in case, test pass when should have failed because didn't testing. way deal use $this->setexpectedexception()
b great when might use information exception. rather using text of exception message prefer use code. have form validation exception packages problems encountered in data 1 exception. extending exception class becomes easy transmit deal of information internal error state external handling code.
c accomplishes same thing b, allows simplifying code relying on more classes. difference between these 2 subtle , tend rely on design aesthetic make decision.
tl; dr: use exception codes rather messages, , design use case rather unit tests.
- Get link
- X
- Other Apps
Comments
Post a Comment