I'm writing a c++ function to generate XML using TinyXML. I'd like to verify that a (relatively small) tree produced by my function gets turned into a string identical to a reference string.
// intended XML:
<element type="correct" />
It seems like the easiest way to do this comparison is to hardcode the reference string into the code:
//assignment
std::string intended = "<element type=\"correct\" />";
However, the backslashes to escape the quotes prevent the comparison from succeeding.
#include <tinyxml.h>
#include <string.h>
TiXmlElement test = TiXmlElement("element");
test.SetAttribute("type", "correct");
TiXmlPrinter printer;
test.Accept(&printer);
ASSERT_EQ(intended, printer.CStr()); // gtests macro
output:
Value of: printer.CStr()
Actual: "<element type="correct" />"
Expected: intended
Which is: "<element type=\"correct\" />"
equals() Method. You can also use the Objects. equals() method in Java to compare two strings either initialized with a new keyword or directly using double-quotes. This method checks whether both the strings objects are equal and if so, return true.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
String comparison in C also possible by using pointers. In this approach, we use pointers to traverse the strings and then compare the characters pointed by the pointer. Explanation: In the code example, We've declared two char arrays str1 ,str2 and then take input for them.
strcmp() in C/C++ It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
On the googletest Primer page I read that ASSERT_EQ()
compares pointers. (which are only equal if they point to the same memory location). If you want to compare C strings, you should use ASSERT_STREQ()
.
ASSERT_STREQ(intended, printer.CStr());
If you want to compare std::string
objects, you can do it this way1:
ASSERT_EQ(intended, printer.Str());
1 Contributed by johnfo through a comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With