-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIMock.hpp
1921 lines (1660 loc) · 66.3 KB
/
IMock.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
/*
IMock 1.1.0
Generated 2022-07-30 18:08:08.797053 UTC
MIT License
Copyright (c) 2022 Samuel Utbult
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <exception>
#include <functional>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace IMock {
namespace Internal {
/// Utility making it possible to call a callback using arguments contained in
/// a tuple.
class Apply {
private:
//! @cond Doxygen_Suppress
// A trick to statically produce a list of integers. The solution has
// been taken from: https://stackoverflow.com/a/7858971/6188897
template<int ...>
struct seq {
};
template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> {
};
template<int ...S>
struct gens<0, S...>{
typedef seq<S...> type;
};
//! @endcond
/// Calls the provided callback with the arguments in the provided
/// tuple.
///
/// Also includes a "seq" making it possible to extract the arguments
/// from the tuple.
///
/// @param callback The function to call.
/// @param arguments The arguments to call the callback with.
/// @return The return value from the callback.
/// @tparam A counter used to extract arguments.
/// @tparam TReturn The return type of the callback.
/// @tparam TArguments The types of the arguments of the callback.
template<int ...S, typename TReturn,
typename ...TArguments>
static TReturn applyWithSeq(
seq<S...>,
std::function<TReturn (TArguments...)> callback,
std::tuple<TArguments...> arguments) {
// Call callback with the extracted arguments.
return callback(std::forward<TArguments>(std::get<S>(
arguments))...);
}
public:
/// Apply is not supposed to be instantiated since it only contains
/// static methods.
Apply() = delete;
/// Calls the provided callback with the arguments in the provided
/// tuple.
///
/// @param callback The function to call.
/// @param arguments The arguments to call the callback with.
/// @return The return value from the callback.
/// @tparam TReturn The return type of the callback.
/// @tparam TArguments The types of the arguments of the callback.
template<typename TReturn, typename ...TArguments>
static TReturn apply(
std::function<TReturn (TArguments...)> callback,
std::tuple<TArguments...> arguments) {
// Create a "gens" with the number of arguments.
return applyWithSeq(typename gens<sizeof...(TArguments)>::type(),
callback,
std::move(arguments));
}
};
}
}
namespace IMock {
namespace Internal {
/// Interface for retrieving a return value.
///
/// @tparam TReturn The return type of the mocked method.
template <typename TReturn>
class IReturnValue {
public:
/// Virtual destructor of IReturnValue.
virtual ~IReturnValue() noexcept {
}
/// Gets the return value.
///
/// NOTICE: The method can only be called once for each instance.
/// Any subsequent calls may result in an exception being thrown.
///
/// @return The return value.
virtual TReturn getReturnValue() = 0;
};
/// Implements IReturnValue to make getReturnValue return void.
class VoidReturnValue : public IReturnValue<void> {
public:
virtual void getReturnValue() override {
}
};
/// Implements IReturnValue to make getReturnValue return the provided value.
///
/// @tparam TReturn The return type of the mocked method.
template <typename TReturn>
class NonVoidReturnValue : public IReturnValue<TReturn> {
private:
/// The value to return.
TReturn _returnValue;
public:
/// Creates a NonVoidReturnValue.
///
/// @param returnValue The value to return.
NonVoidReturnValue(TReturn returnValue)
: _returnValue(std::forward<TReturn>(returnValue)) {
}
virtual TReturn getReturnValue() override {
// Return the stored value.
return _returnValue;
}
};
/// Implements FakeReturnValue to make getReturnValue call the provided fake
/// with the provided arguments and return its return value.
///
/// @tparam TReturn The return type of the mocked method.
/// @tparam TArguments The types of the arguments of the mocked method.
template <typename TReturn, typename ...TArguments>
class FakeReturnValue : public IReturnValue<TReturn> {
private:
/// The fake to call.
std::function<TReturn (TArguments...)> _fake;
/// The arguments to call the fake with.
std::tuple<TArguments...> _arguments;
public:
/// Creates a FakeReturnValue.
///
/// @param fake The fake to call.
/// @param arguments The arguments to call the fake with.
FakeReturnValue(
std::function<TReturn (TArguments...)> fake,
std::tuple<TArguments...> arguments)
: _fake(std::move(fake))
, _arguments(std::move(arguments)) {
}
virtual TReturn getReturnValue() override {
// Forward the call to _fake.
return Apply::apply(_fake, std::move(_arguments));
}
};
}
}
namespace IMock {
namespace Internal {
/// Indicates if a call to a mock case resulted in a match with a return value
/// or if it resulted in no match.
/// @tparam TReturn The return type of the mocked method.
template <typename TReturn>
class CaseMatch {
private:
/// A possible return value.
std::unique_ptr<IReturnValue<TReturn>> _returnValue;
public:
/// Creates a CaseMatch.
///
/// @param returnValue A possible return value.
CaseMatch(std::unique_ptr<IReturnValue<TReturn>> returnValue)
: _returnValue(std::move(returnValue)) {
}
/// Move constructor for CaseMatch.
CaseMatch(CaseMatch&& other)
: _returnValue(std::move(other._returnValue)) {
}
/// Indicates if the call resulted in a match.
///
/// @return True if the call resulted in a match and false otherwise.
bool isMatch() const {
// A match happened if the a return value exists.
return _returnValue.get() != nullptr;
}
/// Gets the return value. Calling this on an instance where isMatch()
/// returns false results in a segmentation fault.
///
/// @return The return value.
IReturnValue<TReturn>& getReturnValue() const {
// Get and return the return value.
return *_returnValue.get();
}
};
}
}
namespace IMock {
namespace Internal {
/// Creates a unique_ptr.
///
/// Named makeUnique using camel casing to not cause any ambiguities with
/// std::make_unique.
///
/// @param arguments Arguments used to create the contained value.
/// @return A created unique_ptr.
/// @tparam TPointer The type of contained value to create.
/// @tparam TArguments The types of the arguments used to create the contained
/// value.
template<typename TPointer, typename... TArguments>
std::unique_ptr<TPointer> makeUnique(TArguments&&... arguments)
{
// Check if std::make_unique is available (introduced in C++14).
#ifdef __cpp_lib_make_unique
// Use std::make_unique to create the unique_ptr since std::make_unique is
// available.
return std::make_unique<TPointer, TArguments...>(
std::forward<TArguments>(arguments)...);
#else
// Create an instance manually and then create a unique_ptr using it since
// std::make_unique is not available.
return std::unique_ptr<TPointer>(
new TPointer(std::forward<TArguments>(arguments)...));
#endif
}
}
}
namespace IMock {
namespace Exception {
/// A class implementing std::exception thrown by IMock when something is wrong.
class MockException : public std::exception {
private:
/// An explanation of what went wrong.
std::string message;
public:
/// Creates a MockException.
///
/// @param message An explanation of what went wrong.
MockException(std::string message)
: message(message) {
}
/// An override of std::exception::what() that returns the message.
///
/// @return A constant pointer to the message.
const char* what() const noexcept override {
// Return a constant pointer to the message.
return message.c_str();
}
};
}
}
namespace IMock {
namespace Exception {
/// Thrown when a call was made to a method that has been mocked but the
/// arguments does not match any mocked arguments.
class UnmockedCallException : public MockException {
public:
/// Creates an UnmockedCallException.
///
/// @param callString A string describing how the call was made.
UnmockedCallException(
std::string callString)
: MockException(getMessage(std::move(callString))) {
}
private:
/// Creates an exception message.
///
/// @param callString A string describing how the call was made.
/// @return A generated exception message.
static std::string getMessage(
std::string callString) {
// Create and return a message containing callString.
return "The call "
+ callString
+ " does not match any mocked case.";
}
};
}
}
namespace IMock {
namespace Internal {
/// Interface for a mocked case.
///
/// @tparam TReturn The return type of the mocked method.
/// @tparam TArguments The types of the arguments to the method.
template <typename TReturn, typename ...Arguments>
class ICase {
public:
/// Virtual destructor of ICase.
virtual ~ICase() noexcept {
}
/// Checks if the provided arguments matches the case.
///
/// @param arguments The arguments the mocked method was called with.
/// The arguments will never be used again if the function indicates a
/// match, which means the values can safely be moved.
/// @return A CaseMatch indicating if the arguments resulted in a match.
virtual CaseMatch<TReturn> matches(std::tuple<Arguments...>& arguments)
= 0;
};
}
}
namespace IMock {
namespace Internal {
/// Interface for a method in a mock without any specified argument types or
/// return value type.
class IMockMethodNonGeneric {
public:
/// Virtual destructor of IMockMethodNonGeneric.
virtual ~IMockMethodNonGeneric() noexcept {
}
};
}
}
namespace IMock {
namespace Internal {
/// Joins vectors of strings using a provided delimiter.
class JoinStrings {
public:
/// JoinStrings is not supposed to be instantiated since it only
/// contains static methods.
JoinStrings() = delete;
/// Joins a vector of strings using a provided delimiter.
///
/// @param delimiter The string to insert between each string.
/// @param strings The vector of strings to be joined.
static std::string joinStrings(
std::string delimiter,
std::vector<std::string> strings) {
// Create an empty list to store the result.
std::string result = "";
// Get the beginning of the string vector.
std::vector<std::string>::iterator begin = strings.begin();
// Process each string.
for(std::vector<std::string>::iterator iterator = begin;
iterator < strings.end();
iterator++) {
// Check if the current string is a non-initial string.
if(iterator > begin) {
// Append the delimiter if that's the case.
result.append(delimiter);
}
// Append the current string.
result.append(*iterator);
}
// Return the joined string.
return result;
}
};
}
}
namespace IMock {
namespace Internal {
/// Contains a call count that can be increased and retrieved.
class MutableCallCount {
private:
// The call count.
int _callCount;
public:
/// Creates a MutableCallCount by initializing the call count with zero.
MutableCallCount()
: _callCount(0) {
}
/// Increases the call count by one.
void increase() {
_callCount++;
}
/// Gets the call count.
///
/// @return The call count.
int getCallCount() const {
// Return the call count.
return _callCount;
}
};
}
}
namespace IMock {
namespace Internal {
/// Converts values to strings.
class ToString {
private:
// A trick to see if two types can use the insertion operator.
// The solution has been taken from:
// https://stackoverflow.com/a/22759544/6188897
///
/// @tparam S The stream to stream to.
/// @tparam T The object to be streamed.
template<typename S, typename T>
class is_streamable
{
private:
template<typename SS, typename TT>
static auto test(int) -> decltype(
std::declval<SS&>() << std::declval<TT>(),
std::true_type());
template<typename, typename>
static auto test(...) -> std::false_type;
public:
static const bool value = decltype(test<S,T>(0))::value;
};
public:
/// ToString is not supposed to be instantiated since it only contains
/// static methods.
ToString() = delete;
/// Converts a value to a string.
///
/// Uses the insertion operator since it's available.
///
/// @param value The value to be converted.
/// @return A string representation of the value.
/// @tparam TValue The value to be converted to a string.
template <typename TValue>
static std::string toString(
typename std::enable_if<
is_streamable<std::stringstream, TValue>::value,
TValue>::type value) {
// Create a stringstream.
std::stringstream out;
// Append the value.
out << value;
// Create a string and return it.
return out.str();
}
/// Converts a value to a string.
///
/// Returns a question mark since the insertion operator is unavailable.
///
/// @param value The value to be converted.
/// @return A string representation of the value.
/// @tparam TValue The value to be converted to a string.
template <typename TValue>
static std::string toString(
typename std::enable_if<
!is_streamable<std::stringstream, TValue>::value,
TValue>::type value) {
// Return a question mark.
return "?";
}
/// Converts a number of values to strings.
/// Uses ToString::toString internally.
///
/// @param values The values to be converted.
/// @return String representations of the values.
/// @tparam TValue The values to be converted to strings.
template <typename ...TValue>
static std::vector<std::string> toStrings(TValue... values) {
// Call toString for each value.
std::vector<std::string> strings = {
toString<TValue>(std::forward<TValue>(values))...
};
// Return the strings.
return strings;
}
};
}
}
namespace IMock {
namespace Exception {
/// Thrown when a method is expected to have been called a certain number of
/// times but actually was called a different number of times.
class WrongCallCountException : public MockException {
public:
/// Creates a WrongCallCountException.
///
/// @param expectedCallCount The number of calls expected to have been
/// made.
/// @param actualCallCount The number of calls that has actually been
/// made.
WrongCallCountException(
int expectedCallCount,
int actualCallCount)
: MockException(getMessage(
expectedCallCount,
actualCallCount)) {
}
private:
/// Creates an exception message.
///
/// @param expectedCallCount The number of calls expected to have been
/// made.
/// @param actualCallCount The number of calls that has actually been
/// made.
/// @return A generated exception message.
static std::string getMessage(
int expectedCallCount,
int actualCallCount) {
// Create a stringstream.
std::stringstream out;
// Append the expected number of calls.
out << "Expected the method to be called "
<< expectedCallCount
<< " time";
// Check if the expected number of calls should be referred to in
// plural.
if(expectedCallCount != 1) {
// Append an "s" if that's the case.
out << "s";
}
// Append the actual number of calls.
out << " but it was called "
<< actualCallCount
<< " time";
// Check if the actual number of calls should be referred to in
// plural.
if(actualCallCount != 1) {
// Append an "s" if that's the case.
out << "s";
}
// Append a period.
out << ".";
// Create a string and return it.
return out.str();
}
};
}
}
namespace IMock {
/// Is used to access the number of times a mock case has been called or to
/// verify that a mock case has been called a certain number of times.
class CallCount {
private:
/// A pointer to a MutableCallCount containing the call count.
std::shared_ptr<Internal::MutableCallCount> _callCount;
public:
/// Creates a CallCount.
///
/// @param callCount A MutableCallCount to get the call count from.
CallCount(
std::shared_ptr<Internal::MutableCallCount> callCount)
: _callCount(std::move(callCount)) {
}
/// Gets the number of times the underlying mock case currently has been
/// called.
///
/// @return The number of times the underlying mock case currently has
/// been called.
int getCallCount() const {
// Call getCallCount to get the call count and then return it.
return _callCount->getCallCount();
}
/// Verify the underlying mock case has been called a certain number of
/// times.
///
/// @param expectedCallCount The number of times the mock case should
/// have been called.
/// @throws Throws a WrongCallCountException if the actual call count
/// differs from the expected call count.
void verifyCallCount(int expectedCallCount) const {
// Get the actual call count.
int actualCallCount = getCallCount();
// Check if the call counts are equal.
if(actualCallCount != expectedCallCount) {
// Throw a WrongCallCountException if that's not the case.
throw Exception::WrongCallCountException(
expectedCallCount,
actualCallCount);
}
}
/// Verify the underlying mock case has been called exactly once.
///
/// @throws Throws a WrongCallCountException if the mock case has not
/// been called exactly once.
void verifyCalledOnce() const {
// Call verifyCallCount with one.
verifyCallCount(1);
}
/// Verify the underlying mock case has never been called.
///
/// @throws Throws a WrongCallCountException if the mock case has been
/// called at least once.
void verifyNeverCalled() const {
// Call verifyCallCount with zero.
verifyCallCount(0);
}
};
}
namespace IMock {
namespace Internal {
/// A mocked method containing a number of mock cases.
///
/// @tparam TReturn The return type of the mocked method.
/// @tparam TArguments The types of the arguments of the mocked method.
template <typename TReturn, typename ...TArguments>
class MockMethod : public IMockMethodNonGeneric {
private:
/// Contains information about one mock case.
class InnerMockCase {
public:
/// The mock case's ICase.
std::unique_ptr<ICase<TReturn, TArguments...>> _mockCase;
/// A MutableCallCount keeping track of how many times the mock
/// case has been called.
std::shared_ptr<MutableCallCount> _callCount;
/// The next mock case.
std::unique_ptr<InnerMockCase> _next;
/// Creates a InnerMockCase.
///
/// @param mockCase The mock case's ICase.
/// @param callCount A MutableCallCount keeping track of how
/// many times the mock case has been called.
/// @param next The next mock case.
InnerMockCase(
std::unique_ptr<ICase<TReturn, TArguments...>> mockCase,
std::shared_ptr<MutableCallCount> callCount,
std::unique_ptr<InnerMockCase> next)
: _mockCase(std::move(mockCase))
, _callCount(std::move(callCount))
, _next(std::move(next)) {
}
};
/// The most recently mock case to have been added.
std::unique_ptr<InnerMockCase> _topMockCase;
/// A string describing how a call is made to the method being mocked.
std::string _methodString;
public:
/// Creates a MockMethod without any mock cases.
///
/// @param methodString A string describing how a call is made to the
/// method being mocked.
MockMethod(std::string methodString)
: _topMockCase(std::unique_ptr<InnerMockCase>(nullptr))
, _methodString(std::move(methodString)) {
}
/// Destructs the MockMethod by deleting all InnerMockCase instances
/// iteratively to not cause any stack overflows.
~MockMethod() noexcept {
// Declare a pointer for mock cases and initialize it with the top
// mock case while releasing its unique_ptr.
InnerMockCase* mockCase = _topMockCase.release();
// Iterate while mock cases exist.
while(mockCase != nullptr) {
// Get the next mock case while releasing its unique_ptr.
InnerMockCase* nextMockCase = mockCase->_next.release();
// Delete the mock case.
delete mockCase;
// Assign the next mock case to mockCase to continue with it.
mockCase = nextMockCase;
}
}
/// Adds a new mock case.
///
/// @param mockCase A mock case to add.
CallCount addCase(
std::unique_ptr<ICase<TReturn, TArguments...>> mockCase) {
// Create a MutableCallCount for the mock case.
std::shared_ptr<MutableCallCount> callCountPointer
= std::make_shared<MutableCallCount>();
// Create a InnerMockCase and assign it to _topMockCase.
_topMockCase = Internal::makeUnique<InnerMockCase>(
std::move(mockCase),
callCountPointer,
std::move(_topMockCase));
// Create a CallCount for the mock case.
CallCount callCount(callCountPointer);
// Return the CallCount.
return callCount;
}
/// Call this when the method to mock is called.
///
/// @param arguments The arguments of the call.
/// @return The return value from the first matching mock case.
/// @throws Throws an UnmockedCallException if the arguments does not
/// match any mock case.
TReturn onCall(TArguments... arguments) {
// Create a tuple from the arguments.
std::tuple<TArguments...> tupleArguments(
std::forward<TArguments>(arguments)...);
// Declare a pointer for mock cases and initialize it with the top
// mock case.
InnerMockCase* mockCase = _topMockCase.get();
// Iterate while mock cases exist.
while(mockCase != nullptr) {
// Check if the current mock case matches the arguments.
CaseMatch<TReturn> caseMatch = mockCase->_mockCase->matches(
tupleArguments);
// Get if a match happened.
bool match = caseMatch.isMatch();
// Check if a match happened.
if(match) {
// If so, increase the call count.
mockCase->_callCount->increase();
// And then, return the return value.
return caseMatch
.getReturnValue()
.getReturnValue();
}
else {
// Otherwise, continue with the next mock case.
mockCase = mockCase->_next.get();
}
}
// No mock case matches the arguments.
// Create a call string from the arguments.
std::string callString = getCallString(std::move(tupleArguments));
// Throw an UnmockedCallException.
throw Exception::UnmockedCallException(callString);
}
private:
/// Create a call string from the provided arguments.
///
/// @param arguments The arguments of the call.
/// @return A string describing how the call was made.
std::string getCallString(std::tuple<TArguments...> arguments) const {
// Convert the arguments to strings.
std::vector<std::string> stringArguments
= Apply::apply<std::vector<std::string>, TArguments...>(
std::function<std::vector<std::string> (TArguments...)>(
ToString::toStrings<TArguments...>),
std::move(arguments));
// Join the argument strings.
std::string argumentsString = JoinStrings::joinStrings(
", ",
std::move(stringArguments));
// Create a call string.
std::string callString
= _methodString
+ "(" + argumentsString + ")";
// Return the call string.
return callString;
}
};
}
}
namespace IMock {
namespace Internal {
/// Casts a value of any type to a value of any other type with regards to the
/// raw memory using a union. Use with caution.
/// @param source The value to cast from.
/// @return The casted value.
/// @tparam TTarget The type to convert the value to.
/// @tparam TSource The type to convert the value from.
template <typename TTarget, typename TSource>
#if defined(__GNUG__) && !defined(__clang__)
[[gnu::optimize("no-devirtualize")]]
#endif
TTarget union_cast(TSource source) {
// Create a union with a member each for the source and the target.
union
{
TSource source;
TTarget target;
} castUnion;
// Store the source in the union.
castUnion.source = source;
// Retrieve the target from the union and return it.
return castUnion.target;
}
}
}
namespace IMock {
namespace Exception {
/// Thrown when a method is called that has not been mocked.
class UnknownCallException : public MockException {
public:
/// Creates an UnknownCallException.
UnknownCallException()
: MockException("A call was made to a method that has not been "
"mocked.") {
}
};
}
}
namespace IMock {
namespace Internal {
/// Contains a static function to call if a call has been made to a method
/// without any mock cases.
class UnknownCall {
public:
/// UnknownCall is not supposed to be instantiated since it only
/// contains a static method.
UnknownCall() = delete;
/// Call this if a call has been made to a method without any mock
/// cases.
static void onUnknownCall(void*) {
// Throw an UnknownCallException.
throw Exception::UnknownCallException();
}
};
}
}
namespace IMock {
namespace Internal {
/// Specifies an method offset within a virtual table.
typedef unsigned int VirtualTableOffset;
/// Specifies the size of a virtual table.
typedef VirtualTableOffset VirtualTableSize;
}
}
namespace IMock {
namespace Internal {
// Define a macro creating a virtual method returning its own virtual table
// offset.
#define offset0(id) \
virtual VirtualTableOffset offset ## id() {\
return id;\
}\
// Calls offset0 16 times, creating 16 methods.
#define offset1(id) \
offset0(id ## 0) \
offset0(id ## 1) \
offset0(id ## 2) \
offset0(id ## 3) \
offset0(id ## 4) \
offset0(id ## 5) \
offset0(id ## 6) \
offset0(id ## 7) \
offset0(id ## 8) \
offset0(id ## 9) \
offset0(id ## A) \
offset0(id ## B) \
offset0(id ## C) \
offset0(id ## D) \
offset0(id ## E) \
offset0(id ## F) \
// Calls offset1 16 times, creating 256 methods.
#define offset2(id) \
offset1(id ## 0) \
offset1(id ## 1) \
offset1(id ## 2) \
offset1(id ## 3) \
offset1(id ## 4) \
offset1(id ## 5) \
offset1(id ## 6) \
offset1(id ## 7) \
offset1(id ## 8) \
offset1(id ## 9) \
offset1(id ## A) \
offset1(id ## B) \
offset1(id ## C) \
offset1(id ## D) \
offset1(id ## E) \
offset1(id ## F) \
// Calls offset2 16 times, creating 4096 methods.