简体   繁体   中英

Test case to fail this code?

I have to maintain code from a contractor. It has this "interesting" snippet:

String webServicesValue = 
  webResponse.substring(webResponse.indexOf("<" + fieldName + ">") + 
                        fieldName.length() + 2, 
                        webResponse.indexOf("</" + fieldName + ">"));

It took me a few minutes to understand what he's trying to do.

It seems to be a WTF code, but my colleague suggested, "If it ain't broken, don't fix it." I'm wondering if this code will ever fail. It seems to be working so far, and I honestly can't think of a test case to fail this.

Thanks,

Yes. It will throw an Exception if "<fieldname>" is not present in the response. Specifically it will try to call webResponse.substring(fieldName.length() + 1, -1);

"<fieldname/>" will cause similar problems, as will any attributes on the element.

And if you get "<fieldname> ... <fieldname> ... </fieldName> ... </fieldName>", you'll get the wrong answer.

EDIT: in the light of followup discussions, I'd say that this code should be rewritten to use a proper XML parser ... unless you / your team can guarantee that the code will never have to deal with problematic XML. XML simply allows too many valid (and invalid) variations to deal with by ad-hoc string manipulation.

如果您收到<fieldname/>会发生什么?

Instead of manually parsing XML it's better to use a real XML parser. There are all kinds of corner cases that are hard to cover with plain string manipulation. It will be more readable with a real parser also. It's best to consider XML data to be binary data, especially when taking all the possible character encodings into consideration.

In addition to Igor Brejc and Stephen C's responses above, there's CDATA:

<fieldname><![CDATA[ I am not really </fieldname> ]]></fieldname>

or even

<othertag>
  <![CDATA[ I am not really <fieldname> and there is no closing tag ]]>
</othertag>

I would suggest re-writing it in that case. If it is not easy to understand, then it is more difficult to test.

  • Nested tags. You'll start at the first open tag, skip any others that exist and stop on the first close tag instead of the matching close tag.
  • There is a close tag somewhere before the open tag (you're searching for the close tag from the beginning of the string, not the end of the open tag)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM