File indexing completed on 2025-01-05 05:00:01

0001 /*
0002  * SPDX-FileCopyrightText: 2014 Kevin Ottens <ervin@kde.org>
0003  SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0004 */
0005 
0006 
0007 #include <testlib/qtest_zanshin.h>
0008 
0009 #include "utils/mockobject.h"
0010 
0011 using mockitopp::matcher::any;
0012 
0013 using namespace Utils;
0014 
0015 class FakeInterface
0016 {
0017 public:
0018     FakeInterface() {}
0019     virtual ~FakeInterface() {}
0020     virtual void doSomething() = 0;
0021     virtual int computeMe(QString input) = 0;
0022 };
0023 
0024 class MockObjectTest : public QObject
0025 {
0026     Q_OBJECT
0027 private slots:
0028     void testBasics()
0029     {
0030         MockObject<FakeInterface> mock;
0031         mock(&FakeInterface::doSomething).when().thenReturn();
0032         mock(&FakeInterface::doSomething).when().thenThrow("exception");
0033         for (int i = 0; i < 10; i++) {
0034             mock(&FakeInterface::computeMe).when(QStringLiteral("A")).thenReturn(0);
0035             mock(&FakeInterface::computeMe).when(QStringLiteral("B")).thenReturn(1);
0036             mock(&FakeInterface::computeMe).when(QStringLiteral("C")).thenReturn(-1);
0037             mock(&FakeInterface::computeMe).when(QStringLiteral("Foo")).thenReturn(-1);
0038         }
0039         QSharedPointer<FakeInterface> iface1 = mock.getInstance();
0040         QSharedPointer<FakeInterface> iface2 = mock.getInstance(); // Shouldn't cause a crash later
0041 
0042         QCOMPARE(iface1.data(), iface2.data());
0043 
0044         iface1->doSomething();
0045         try {
0046             iface2->doSomething();
0047             QFAIL("No exception thrown");
0048         } catch (...) {
0049             // We expect to catch something
0050         }
0051 
0052         for (int i = 0; i < 10; i++) {
0053             QCOMPARE(iface1->computeMe(QStringLiteral("A")), 0);
0054             QCOMPARE(iface2->computeMe(QStringLiteral("B")), 1);
0055             QCOMPARE(iface1->computeMe(QStringLiteral("C")), -1);
0056             QCOMPARE(iface2->computeMe(QStringLiteral("Foo")), -1);
0057         }
0058 
0059         QVERIFY(mock(&FakeInterface::doSomething).when().exactly(2));
0060         QVERIFY(mock(&FakeInterface::computeMe).when(any<QString>()).exactly(40));
0061     }
0062 };
0063 
0064 ZANSHIN_TEST_MAIN(MockObjectTest)
0065 
0066 #include "mockobjecttest.moc"