0

Is it safe to overload functions/methods in QTest files?

I need the function/method to give a different result during the tests. The test works when I run it but will it cause any issues like so? or is there a better way to do it?

For QT5 QTest, Assuming we have Class1.cpp with:

QString Class1::func1() {
return "cat";
}

Is it okay to overload it like this for testing only in testClass1.cpp like so?

void TestClass1::testFunc1() {
QVerify(Class1::func1() == "bat")
}

QString Class1::func1() {
return "bat";
}
  • 1
    If you have 2 different definitions for `Class1::func1()`, you have ODR violation. Ill formed program, NDR. – Jarod42 Mar 28 '22 at 08:13
  • 1
    if you test code that is different from the one you want to test, then you arent testing the code you should be testing – 463035818_is_not_an_ai Mar 28 '22 at 08:30
  • @Jarod42 - I understand, but it works. Compiler doesn't complain and test and compiled versions each are using their own code. Is there a better way to do this then? – user16551018 Mar 28 '22 at 08:49
  • @463035818_is_not_a_number - My test code isn't different then what I want to test. Unit tests by nature test 1 specific function no? Why do I need to load up the entire GUI and everything under the sink, if all I need to test is 1 specific thing that never touches the GUI? – user16551018 Mar 28 '22 at 08:50
  • my advice is to write code such that it can be tested. If you need to apply some trickery to test it then you better rewrite it such that it can be tested without trickery. There is not much context, but dependency injection is a buzzword that might help – 463035818_is_not_an_ai Mar 28 '22 at 08:51
  • @463035818_is_not_a_number - I'll take a look, the problem here is the code isn't mine. I am simply adding a simple extension to it. I'll be stepping on way too many landmines if I plan to rewrite everything. So I would prefer to limit that as much as possible. – user16551018 Mar 28 '22 at 09:02
  • To be clear, is "Class1.cpp" compiled for Test application? If not, you are fine, else you have ill-formaed program and anything can happen. – Jarod42 Mar 28 '22 at 09:29
  • @Jarod42 - It technically should be since it is called within one of the methods. And by anything can happen you mean it would depend on the compiler on how it handles it? Is there any suggested alternatives? #ifdef maybe or something else? – user16551018 Mar 28 '22 at 21:32
  • With `virtual` `func1` (and even interface class), you might substitute `Class1` by `TestClass1`. – Jarod42 Mar 29 '22 at 07:59

1 Answers1

0

You can use googlemock to write a mock of your class, as stated in the Qt doc https://doc.qt.io/qt-5/qttest-best-practices-qdoc.html#writing-testable-code