OpenCores
URL https://opencores.org/ocsvn/s80186/s80186/trunk

Subversion Repositories s80186

[/] [s80186/] [trunk/] [vendor/] [googletest/] [googletest/] [docs/] [V1_5_FAQ.md] - Blame information for rev 2

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 jamieiles
 
2
 
3
If you cannot find the answer to your question here, and you have read
4
[Primer](V1_5_Primer.md) and [AdvancedGuide](V1_5_AdvancedGuide.md), send it to
5
googletestframework@googlegroups.com.
6
 
7
## Why should I use Google Test instead of my favorite C++ testing framework? ##
8
 
9
First, let's say clearly that we don't want to get into the debate of
10
which C++ testing framework is **the best**.  There exist many fine
11
frameworks for writing C++ tests, and we have tremendous respect for
12
the developers and users of them.  We don't think there is (or will
13
be) a single best framework - you have to pick the right tool for the
14
particular task you are tackling.
15
 
16
We created Google Test because we couldn't find the right combination
17
of features and conveniences in an existing framework to satisfy _our_
18
needs.  The following is a list of things that _we_ like about Google
19
Test.  We don't claim them to be unique to Google Test - rather, the
20
combination of them makes Google Test the choice for us.  We hope this
21
list can help you decide whether it is for you too.
22
 
23
  * Google Test is designed to be portable.  It works where many STL types (e.g. `std::string` and `std::vector`) don't compile.  It doesn't require exceptions or RTTI.  As a result, it runs on Linux, Mac OS X, Windows and several embedded operating systems.
24
  * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle.
25
  * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`.  It doesn't require a new set of macros or special functions.
26
  * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them.
27
  * No framework can anticipate all your needs, so Google Test provides `EXPECT_PRED*` to make it easy to extend your assertion vocabulary.  For a nicer syntax, you can define your own assertion macros trivially in terms of `EXPECT_PRED*`.
28
  * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions.
29
  * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop.
30
  * You can decide which tests to run using name patterns.  This saves time when you want to quickly reproduce a test failure.
31
 
32
## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
33
 
34
(Answered by Trevor Robinson)
35
 
36
Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or
37
`msvc\gtest.sln`. Go through the migration wizard to migrate the
38
solution and project files to Visual Studio 2008. Select
39
`Configuration Manager...` from the `Build` menu. Select `` from
40
the `Active solution platform` dropdown.  Select `x64` from the new
41
platform dropdown, leave `Copy settings from` set to `Win32` and
42
`Create new project platforms` checked, then click `OK`. You now have
43
`Win32` and `x64` platform configurations, selectable from the
44
`Standard` toolbar, which allow you to toggle between building 32-bit or
45
64-bit binaries (or both at once using Batch Build).
46
 
47
In order to prevent build output files from overwriting one another,
48
you'll need to change the `Intermediate Directory` settings for the
49
newly created platform configuration across all the projects. To do
50
this, multi-select (e.g. using shift-click) all projects (but not the
51
solution) in the `Solution Explorer`. Right-click one of them and
52
select `Properties`. In the left pane, select `Configuration Properties`,
53
and from the `Configuration` dropdown, select `All Configurations`.
54
Make sure the selected platform is `x64`. For the
55
`Intermediate Directory` setting, change the value from
56
`$(PlatformName)\$(ConfigurationName)` to
57
`$(OutDir)\$(ProjectName)`. Click `OK` and then build the
58
solution. When the build is complete, the 64-bit binaries will be in
59
the `msvc\x64\Debug` directory.
60
 
61
## Can I use Google Test on MinGW? ##
62
 
63
We haven't tested this ourselves, but Per Abrahamsen reported that he
64
was able to compile and install Google Test successfully when using
65
MinGW from Cygwin.  You'll need to configure it with:
66
 
67
`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
68
 
69
You should be able to replace the `-mno-cygwin` option with direct links
70
to the real MinGW binaries, but we haven't tried that.
71
 
72
Caveats:
73
 
74
  * There are many warnings when compiling.
75
  * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW.
76
 
77
We also have reports on successful cross compilation of Google Test MinGW binaries on Linux using [these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) on the WxWidgets site.
78
 
79
Please contact `googletestframework@googlegroups.com` if you are
80
interested in improving the support for MinGW.
81
 
82
## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ##
83
 
84
Due to some peculiarity of C++, it requires some non-trivial template
85
meta programming tricks to support using `NULL` as an argument of the
86
`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where
87
it's most needed (otherwise we make the implementation of Google Test
88
harder to maintain and more error-prone than necessary).
89
 
90
The `EXPECT_EQ()` macro takes the _expected_ value as its first
91
argument and the _actual_ value as the second. It's reasonable that
92
someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this
93
indeed was requested several times. Therefore we implemented it.
94
 
95
The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the
96
assertion fails, you already know that `ptr` must be `NULL`, so it
97
doesn't add any information to print ptr in this case. That means
98
`EXPECT_TRUE(ptr ! NULL)` works just as well.
99
 
100
If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll
101
have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`,
102
we don't have a convention on the order of the two arguments for
103
`EXPECT_NE`. This means using the template meta programming tricks
104
twice in the implementation, making it even harder to understand and
105
maintain. We believe the benefit doesn't justify the cost.
106
 
107
Finally, with the growth of Google Mock's [matcher](../../CookBook.md#using-matchers-in-google-test-assertions) library, we are
108
encouraging people to use the unified `EXPECT_THAT(value, matcher)`
109
syntax more often in tests. One significant advantage of the matcher
110
approach is that matchers can be easily combined to form new matchers,
111
while the `EXPECT_NE`, etc, macros cannot be easily
112
combined. Therefore we want to invest more in the matchers than in the
113
`EXPECT_XX()` macros.
114
 
115
## Does Google Test support running tests in parallel? ##
116
 
117
Test runners tend to be tightly coupled with the build/test
118
environment, and Google Test doesn't try to solve the problem of
119
running tests in parallel.  Instead, we tried to make Google Test work
120
nicely with test runners.  For example, Google Test's XML report
121
contains the time spent on each test, and its `gtest_list_tests` and
122
`gtest_filter` flags can be used for splitting the execution of test
123
methods into multiple processes.  These functionalities can help the
124
test runner run the tests in parallel.
125
 
126
## Why don't Google Test run the tests in different threads to speed things up? ##
127
 
128
It's difficult to write thread-safe code.  Most tests are not written
129
with thread-safety in mind, and thus may not work correctly in a
130
multi-threaded setting.
131
 
132
If you think about it, it's already hard to make your code work when
133
you know what other threads are doing.  It's much harder, and
134
sometimes even impossible, to make your code work when you don't know
135
what other threads are doing (remember that test methods can be added,
136
deleted, or modified after your test was written).  If you want to run
137
the tests in parallel, you'd better run them in different processes.
138
 
139
## Why aren't Google Test assertions implemented using exceptions? ##
140
 
141
Our original motivation was to be able to use Google Test in projects
142
that disable exceptions.  Later we realized some additional benefits
143
of this approach:
144
 
145
  1. Throwing in a destructor is undefined behavior in C++.  Not using exceptions means Google Test's assertions are safe to use in destructors.
146
  1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing.
147
  1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code:
148
```
149
try { ... ASSERT_TRUE(...) ... }
150
catch (...) { ... }
151
```
152
The above code will pass even if the `ASSERT_TRUE` throws.  While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test.
153
 
154
The downside of not using exceptions is that `ASSERT_*` (implemented
155
using `return`) will only abort the current function, not the current
156
`TEST`.
157
 
158
## Why do we use two different macros for tests with and without fixtures? ##
159
 
160
Unfortunately, C++'s macro system doesn't allow us to use the same
161
macro for both cases.  One possibility is to provide only one macro
162
for tests with fixtures, and require the user to define an empty
163
fixture sometimes:
164
 
165
```
166
class FooTest : public ::testing::Test {};
167
 
168
TEST_F(FooTest, DoesThis) { ... }
169
```
170
or
171
```
172
typedef ::testing::Test FooTest;
173
 
174
TEST_F(FooTest, DoesThat) { ... }
175
```
176
 
177
Yet, many people think this is one line too many. :-) Our goal was to
178
make it really easy to write tests, so we tried to make simple tests
179
trivial to create.  That means using a separate macro for such tests.
180
 
181
We think neither approach is ideal, yet either of them is reasonable.
182
In the end, it probably doesn't matter much either way.
183
 
184
## Why don't we use structs as test fixtures? ##
185
 
186
We like to use structs only when representing passive data.  This
187
distinction between structs and classes is good for documenting the
188
intent of the code's author.  Since test fixtures have logic like
189
`SetUp()` and `TearDown()`, they are better defined as classes.
190
 
191
## Why are death tests implemented as assertions instead of using a test runner? ##
192
 
193
Our goal was to make death tests as convenient for a user as C++
194
possibly allows.  In particular:
195
 
196
  * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect.  The death test would be written in C++, while the runner spec may or may not be.  A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative.
197
  * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn.
198
  * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will.  You are not limited to one death test per test method. For example, you can write something like:
199
```
200
    if (FooCondition()) {
201
      ASSERT_DEATH(Bar(), "blah");
202
    } else {
203
      ASSERT_EQ(5, Bar());
204
    }
205
```
206
If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users.  The fewer artificial limitations the better.
207
  * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information.  For example,
208
```
209
    const int count = GetCount();  // Only known at run time.
210
    for (int i = 1; i <= count; i++) {
211
      ASSERT_DEATH({
212
        double* buffer = new double[i];
213
        ... initializes buffer ...
214
        Foo(buffer, i)
215
      }, "blah blah");
216
    }
217
```
218
The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
219
 
220
Another interesting thing about `ASSERT_DEATH` is that it calls `fork()`
221
to create a child process to run the death test.  This is lightening
222
fast, as `fork()` uses copy-on-write pages and incurs almost zero
223
overhead, and the child process starts from the user-supplied
224
statement directly, skipping all global and local initialization and
225
any code leading to the given statement.  If you launch the child
226
process from scratch, it can take seconds just to load everything and
227
start running if the test links to many libraries dynamically.
228
 
229
## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
230
 
231
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
232
expected crash won't kill the test program (i.e. the parent process). As a
233
result, any in-memory side effects they incur are observable in their
234
respective sub-processes, but not in the parent process. You can think of them
235
as running in a parallel universe, more or less.
236
 
237
## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ##
238
 
239
If your class has a static data member:
240
 
241
```
242
// foo.h
243
class Foo {
244
  ...
245
  static const int kBar = 100;
246
};
247
```
248
 
249
You also need to define it _outside_ of the class body in `foo.cc`:
250
 
251
```
252
const int Foo::kBar;  // No initializer here.
253
```
254
 
255
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
256
particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc)
257
will generate an "undefined reference" linker error.
258
 
259
## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
260
 
261
Google Test doesn't yet have good support for this kind of tests, or
262
data-driven tests in general. We hope to be able to make improvements in this
263
area soon.
264
 
265
## Can I derive a test fixture from another? ##
266
 
267
Yes.
268
 
269
Each test fixture has a corresponding and same named test case. This means only
270
one test case can use a particular fixture. Sometimes, however, multiple test
271
cases may want to use the same or slightly different fixtures. For example, you
272
may want to make sure that all of a GUI library's test cases don't leak
273
important system resources like fonts and brushes.
274
 
275
In Google Test, you share a fixture among test cases by putting the shared
276
logic in a base test fixture, then deriving from that base a separate fixture
277
for each test case that wants to use this common logic. You then use `TEST_F()`
278
to write tests using each derived fixture.
279
 
280
Typically, your code looks like this:
281
 
282
```
283
// Defines a base test fixture.
284
class BaseTest : public ::testing::Test {
285
  protected:
286
   ...
287
};
288
 
289
// Derives a fixture FooTest from BaseTest.
290
class FooTest : public BaseTest {
291
  protected:
292
    virtual void SetUp() {
293
      BaseTest::SetUp();  // Sets up the base fixture first.
294
      ... additional set-up work ...
295
    }
296
    virtual void TearDown() {
297
      ... clean-up work for FooTest ...
298
      BaseTest::TearDown();  // Remember to tear down the base fixture
299
                             // after cleaning up FooTest!
300
    }
301
    ... functions and variables for FooTest ...
302
};
303
 
304
// Tests that use the fixture FooTest.
305
TEST_F(FooTest, Bar) { ... }
306
TEST_F(FooTest, Baz) { ... }
307
 
308
... additional fixtures derived from BaseTest ...
309
```
310
 
311
If necessary, you can continue to derive test fixtures from a derived fixture.
312
Google Test has no limit on how deep the hierarchy can be.
313
 
314
For a complete example using derived test fixtures, see
315
`samples/sample5_unittest.cc`.
316
 
317
## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
318
 
319
You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
320
`ASSERT_*()` can only be used in `void` functions.
321
 
322
## My death test hangs (or seg-faults). How do I fix it? ##
323
 
324
In Google Test, death tests are run in a child process and the way they work is
325
delicate. To write death tests you really need to understand how they work.
326
Please make sure you have read this.
327
 
328
In particular, death tests don't like having multiple threads in the parent
329
process. So the first thing you can try is to eliminate creating threads
330
outside of `EXPECT_DEATH()`.
331
 
332
Sometimes this is impossible as some library you must use may be creating
333
threads before `main()` is even reached. In this case, you can try to minimize
334
the chance of conflicts by either moving as many activities as possible inside
335
`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
336
leaving as few things as possible in it. Also, you can try to set the death
337
test style to `"threadsafe"`, which is safer but slower, and see if it helps.
338
 
339
If you go with thread-safe death tests, remember that they rerun the test
340
program from the beginning in the child process. Therefore make sure your
341
program can run side-by-side with itself and is deterministic.
342
 
343
In the end, this boils down to good concurrent programming. You have to make
344
sure that there is no race conditions or dead locks in your program. No silver
345
bullet - sorry!
346
 
347
## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
348
 
349
The first thing to remember is that Google Test does not reuse the
350
same test fixture object across multiple tests. For each `TEST_F`,
351
Google Test will create a fresh test fixture object, _immediately_
352
call `SetUp()`, run the test, call `TearDown()`, and then
353
_immediately_ delete the test fixture object. Therefore, there is no
354
need to write a `SetUp()` or `TearDown()` function if the constructor
355
or destructor already does the job.
356
 
357
You may still want to use `SetUp()/TearDown()` in the following cases:
358
  * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
359
  * The Google Test team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use Google Test assertions in a destructor if your code could run on such a platform.
360
  * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`.
361
 
362
## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
363
 
364
If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
365
overloaded or a template, the compiler will have trouble figuring out which
366
overloaded version it should use. `ASSERT_PRED_FORMAT*` and
367
`EXPECT_PRED_FORMAT*` don't have this problem.
368
 
369
If you see this error, you might want to switch to
370
`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
371
message. If, however, that is not an option, you can resolve the problem by
372
explicitly telling the compiler which version to pick.
373
 
374
For example, suppose you have
375
 
376
```
377
bool IsPositive(int n) {
378
  return n > 0;
379
}
380
bool IsPositive(double x) {
381
  return x > 0;
382
}
383
```
384
 
385
you will get a compiler error if you write
386
 
387
```
388
EXPECT_PRED1(IsPositive, 5);
389
```
390
 
391
However, this will work:
392
 
393
```
394
EXPECT_PRED1(*static_cast*(IsPositive), 5);
395
```
396
 
397
(The stuff inside the angled brackets for the `static_cast` operator is the
398
type of the function pointer for the `int`-version of `IsPositive()`.)
399
 
400
As another example, when you have a template function
401
 
402
```
403
template 
404
bool IsNegative(T x) {
405
  return x < 0;
406
}
407
```
408
 
409
you can use it in a predicate assertion like this:
410
 
411
```
412
ASSERT_PRED1(IsNegative**, -5);
413
```
414
 
415
Things are more interesting if your template has more than one parameters. The
416
following won't compile:
417
 
418
```
419
ASSERT_PRED2(*GreaterThan*, 5, 0);
420
```
421
 
422
 
423
as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
424
which is one more than expected. The workaround is to wrap the predicate
425
function in parentheses:
426
 
427
```
428
ASSERT_PRED2(*(GreaterThan)*, 5, 0);
429
```
430
 
431
 
432
## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
433
 
434
Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
435
instead of
436
 
437
```
438
return RUN_ALL_TESTS();
439
```
440
 
441
they write
442
 
443
```
444
RUN_ALL_TESTS();
445
```
446
 
447
This is wrong and dangerous. A test runner needs to see the return value of
448
`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
449
function ignores it, your test will be considered successful even if it has a
450
Google Test assertion failure. Very bad.
451
 
452
To help the users avoid this dangerous bug, the implementation of
453
`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
454
ignored. If you see this warning, the fix is simple: just make sure its value
455
is used as the return value of `main()`.
456
 
457
## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
458
 
459
Due to a peculiarity of C++, in order to support the syntax for streaming
460
messages to an `ASSERT_*`, e.g.
461
 
462
```
463
ASSERT_EQ(1, Foo()) << "blah blah" << foo;
464
```
465
 
466
we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
467
`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
468
content of your constructor/destructor to a private void member function, or
469
switch to `EXPECT_*()` if that works. This section in the user's guide explains
470
it.
471
 
472
## My set-up function is not called. Why? ##
473
 
474
C++ is case-sensitive. It should be spelled as `SetUp()`.  Did you
475
spell it as `Setup()`?
476
 
477
Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
478
wonder why it's never called.
479
 
480
## How do I jump to the line of a failure in Emacs directly? ##
481
 
482
Google Test's failure message format is understood by Emacs and many other
483
IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
484
in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
485
the corresponding source code, or use `C-x `` to jump to the next failure.
486
 
487
## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ##
488
 
489
You don't have to. Instead of
490
 
491
```
492
class FooTest : public BaseTest {};
493
 
494
TEST_F(FooTest, Abc) { ... }
495
TEST_F(FooTest, Def) { ... }
496
 
497
class BarTest : public BaseTest {};
498
 
499
TEST_F(BarTest, Abc) { ... }
500
TEST_F(BarTest, Def) { ... }
501
```
502
 
503
you can simply `typedef` the test fixtures:
504
```
505
typedef BaseTest FooTest;
506
 
507
TEST_F(FooTest, Abc) { ... }
508
TEST_F(FooTest, Def) { ... }
509
 
510
typedef BaseTest BarTest;
511
 
512
TEST_F(BarTest, Abc) { ... }
513
TEST_F(BarTest, Def) { ... }
514
```
515
 
516
## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
517
 
518
The Google Test output is meant to be a concise and human-friendly report. If
519
your test generates textual output itself, it will mix with the Google Test
520
output, making it hard to read. However, there is an easy solution to this
521
problem.
522
 
523
Since most log messages go to stderr, we decided to let Google Test output go
524
to stdout. This way, you can easily separate the two using redirection. For
525
example:
526
```
527
./my_test > googletest_output.txt
528
```
529
 
530
## Why should I prefer test fixtures over global variables? ##
531
 
532
There are several good reasons:
533
  1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other.
534
  1. Global variables pollute the global namespace.
535
  1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common.
536
 
537
## How do I test private class members without writing FRIEND\_TEST()s? ##
538
 
539
You should try to write testable code, which means classes should be easily
540
tested from their public interface. One way to achieve this is the Pimpl idiom:
541
you move all private members of a class into a helper class, and make all
542
members of the helper class public.
543
 
544
You have several other options that don't require using `FRIEND_TEST`:
545
  * Write the tests as members of the fixture class:
546
```
547
class Foo {
548
  friend class FooTest;
549
  ...
550
};
551
 
552
class FooTest : public ::testing::Test {
553
 protected:
554
  ...
555
  void Test1() {...} // This accesses private members of class Foo.
556
  void Test2() {...} // So does this one.
557
};
558
 
559
TEST_F(FooTest, Test1) {
560
  Test1();
561
}
562
 
563
TEST_F(FooTest, Test2) {
564
  Test2();
565
}
566
```
567
  * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
568
```
569
class Foo {
570
  friend class FooTest;
571
  ...
572
};
573
 
574
class FooTest : public ::testing::Test {
575
 protected:
576
  ...
577
  T1 get_private_member1(Foo* obj) {
578
    return obj->private_member1_;
579
  }
580
};
581
 
582
TEST_F(FooTest, Test1) {
583
  ...
584
  get_private_member1(x)
585
  ...
586
}
587
```
588
  * If the methods are declared **protected**, you can change their access level in a test-only subclass:
589
```
590
class YourClass {
591
  ...
592
 protected: // protected access for testability.
593
  int DoSomethingReturningInt();
594
  ...
595
};
596
 
597
// in the your_class_test.cc file:
598
class TestableYourClass : public YourClass {
599
  ...
600
 public: using YourClass::DoSomethingReturningInt; // changes access rights
601
  ...
602
};
603
 
604
TEST_F(YourClassTest, DoSomethingTest) {
605
  TestableYourClass obj;
606
  assertEquals(expected_value, obj.DoSomethingReturningInt());
607
}
608
```
609
 
610
## How do I test private class static members without writing FRIEND\_TEST()s? ##
611
 
612
We find private static methods clutter the header file.  They are
613
implementation details and ideally should be kept out of a .h. So often I make
614
them free functions instead.
615
 
616
Instead of:
617
```
618
// foo.h
619
class Foo {
620
  ...
621
 private:
622
  static bool Func(int n);
623
};
624
 
625
// foo.cc
626
bool Foo::Func(int n) { ... }
627
 
628
// foo_test.cc
629
EXPECT_TRUE(Foo::Func(12345));
630
```
631
 
632
You probably should better write:
633
```
634
// foo.h
635
class Foo {
636
  ...
637
};
638
 
639
// foo.cc
640
namespace internal {
641
  bool Func(int n) { ... }
642
}
643
 
644
// foo_test.cc
645
namespace internal {
646
  bool Func(int n);
647
}
648
 
649
EXPECT_TRUE(internal::Func(12345));
650
```
651
 
652
## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
653
 
654
No. You can use a feature called [value-parameterized tests](V1_5_AdvancedGuide.md#Value_Parameterized_Tests) which
655
lets you repeat your tests with different parameters, without defining it more than once.
656
 
657
## How do I test a file that defines main()? ##
658
 
659
To test a `foo.cc` file, you need to compile and link it into your unit test
660
program. However, when the file contains a definition for the `main()`
661
function, it will clash with the `main()` of your unit test, and will result in
662
a build error.
663
 
664
The right solution is to split it into three files:
665
  1. `foo.h` which contains the declarations,
666
  1. `foo.cc` which contains the definitions except `main()`, and
667
  1. `foo_main.cc` which contains nothing but the definition of `main()`.
668
 
669
Then `foo.cc` can be easily tested.
670
 
671
If you are adding tests to an existing file and don't want an intrusive change
672
like this, there is a hack: just include the entire `foo.cc` file in your unit
673
test. For example:
674
```
675
// File foo_unittest.cc
676
 
677
// The headers section
678
...
679
 
680
// Renames main() in foo.cc to make room for the unit test main()
681
#define main FooMain
682
 
683
#include "a/b/foo.cc"
684
 
685
// The tests start here.
686
...
687
```
688
 
689
 
690
However, please remember this is a hack and should only be used as the last
691
resort.
692
 
693
## What can the statement argument in ASSERT\_DEATH() be? ##
694
 
695
`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
696
wherever `_statement_` is valid. So basically `_statement_` can be any C++
697
statement that makes sense in the current context. In particular, it can
698
reference global and/or local variables, and can be:
699
  * a simple function call (often the case),
700
  * a complex expression, or
701
  * a compound statement.
702
 
703
> Some examples are shown here:
704
 
705
```
706
// A death test can be a simple function call.
707
TEST(MyDeathTest, FunctionCall) {
708
  ASSERT_DEATH(Xyz(5), "Xyz failed");
709
}
710
 
711
// Or a complex expression that references variables and functions.
712
TEST(MyDeathTest, ComplexExpression) {
713
  const bool c = Condition();
714
  ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
715
               "(Func1|Method) failed");
716
}
717
 
718
// Death assertions can be used any where in a function. In
719
// particular, they can be inside a loop.
720
TEST(MyDeathTest, InsideLoop) {
721
  // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
722
  for (int i = 0; i < 5; i++) {
723
    EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
724
                   ::testing::Message() << "where i is " << i);
725
  }
726
}
727
 
728
// A death assertion can contain a compound statement.
729
TEST(MyDeathTest, CompoundStatement) {
730
  // Verifies that at lease one of Bar(0), Bar(1), ..., and
731
  // Bar(4) dies.
732
  ASSERT_DEATH({
733
    for (int i = 0; i < 5; i++) {
734
      Bar(i);
735
    }
736
  },
737
  "Bar has \\d+ errors");}
738
```
739
 
740
`googletest_unittest.cc` contains more examples if you are interested.
741
 
742
## What syntax does the regular expression in ASSERT\_DEATH use? ##
743
 
744
On POSIX systems, Google Test uses the POSIX Extended regular
745
expression syntax
746
(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). On
747
Windows, it uses a limited variant of regular expression syntax. For
748
more details, see the [regular expression syntax](V1_5_AdvancedGuide.md#Regular_Expression_Syntax).
749
 
750
## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
751
 
752
Google Test needs to be able to create objects of your test fixture class, so
753
it must have a default constructor. Normally the compiler will define one for
754
you. However, there are cases where you have to define your own:
755
  * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty.
756
  * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.)
757
 
758
## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
759
 
760
With the Linux pthread library, there is no turning back once you cross the
761
line from single thread to multiple threads. The first time you create a
762
thread, a manager thread is created in addition, so you get 3, not 2, threads.
763
Later when the thread you create joins the main thread, the thread count
764
decrements by 1, but the manager thread will never be killed, so you still have
765
2 threads, which means you cannot safely run a death test.
766
 
767
The new NPTL thread library doesn't suffer from this problem, as it doesn't
768
create a manager thread. However, if you don't control which machine your test
769
runs on, you shouldn't depend on this.
770
 
771
## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
772
 
773
Google Test does not interleave tests from different test cases. That is, it
774
runs all tests in one test case first, and then runs all tests in the next test
775
case, and so on. Google Test does this because it needs to set up a test case
776
before the first test in it is run, and tear it down afterwords. Splitting up
777
the test case would require multiple set-up and tear-down processes, which is
778
inefficient and makes the semantics unclean.
779
 
780
If we were to determine the order of tests based on test name instead of test
781
case name, then we would have a problem with the following situation:
782
 
783
```
784
TEST_F(FooTest, AbcDeathTest) { ... }
785
TEST_F(FooTest, Uvw) { ... }
786
 
787
TEST_F(BarTest, DefDeathTest) { ... }
788
TEST_F(BarTest, Xyz) { ... }
789
```
790
 
791
Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
792
interleave tests from different test cases, we need to run all tests in the
793
`FooTest` case before running any test in the `BarTest` case. This contradicts
794
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
795
 
796
## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ##
797
 
798
You don't have to, but if you like, you may split up the test case into
799
`FooTest` and `FooDeathTest`, where the names make it clear that they are
800
related:
801
 
802
```
803
class FooTest : public ::testing::Test { ... };
804
 
805
TEST_F(FooTest, Abc) { ... }
806
TEST_F(FooTest, Def) { ... }
807
 
808
typedef FooTest FooDeathTest;
809
 
810
TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
811
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
812
```
813
 
814
## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
815
 
816
If you use a user-defined type `FooType` in an assertion, you must make sure
817
there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
818
defined such that we can print a value of `FooType`.
819
 
820
In addition, if `FooType` is declared in a name space, the `<<` operator also
821
needs to be defined in the _same_ name space.
822
 
823
## How do I suppress the memory leak messages on Windows? ##
824
 
825
Since the statically initialized Google Test singleton requires allocations on
826
the heap, the Visual C++ memory leak detector will report memory leaks at the
827
end of the program run. The easiest way to avoid this is to use the
828
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
829
statically initialized heap objects. See MSDN for more details and additional
830
heap check/debug routines.
831
 
832
## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ##
833
 
834
You may get a number of the following linker error or warnings if you
835
attempt to link your test project with the Google Test library when
836
your project and the are not built using the same compiler settings.
837
 
838
  * LNK2005: symbol already defined in object
839
  * LNK4217: locally defined symbol 'symbol' imported in function 'function'
840
  * LNK4049: locally defined symbol 'symbol' imported
841
 
842
The Google Test project (gtest.vcproj) has the Runtime Library option
843
set to /MT (use multi-threaded static libraries, /MTd for debug). If
844
your project uses something else, for example /MD (use multi-threaded
845
DLLs, /MDd for debug), you need to change the setting in the Google
846
Test project to match your project's.
847
 
848
To update this setting open the project properties in the Visual
849
Studio IDE then select the branch Configuration Properties | C/C++ |
850
Code Generation and change the option "Runtime Library".  You may also try
851
using gtest-md.vcproj instead of gtest.vcproj.
852
 
853
## I put my tests in a library and Google Test doesn't run them. What's happening? ##
854
Have you read a
855
[warning](V1_5_Primer.md#important-note-for-visual-c-users) on
856
the Google Test Primer page?
857
 
858
## I want to use Google Test with Visual Studio but don't know where to start. ##
859
Many people are in your position and one of the posted his solution to
860
our mailing list. Here is his link:
861
http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html.
862
 
863
## My question is not covered in your FAQ! ##
864
 
865
If you cannot find the answer to your question in this FAQ, there are
866
some other resources you can use:
867
 
868
  1. read other [wiki pages](http://code.google.com/p/googletest/w/list),
869
  1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics),
870
  1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.).
871
 
872
Please note that creating an issue in the
873
[issue tracker](http://code.google.com/p/googletest/issues/list) is _not_
874
a good way to get your answer, as it is monitored infrequently by a
875
very small number of people.
876
 
877
When asking a question, it's helpful to provide as much of the
878
following information as possible (people cannot help you if there's
879
not enough information in your question):
880
 
881
  * the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version),
882
  * your operating system,
883
  * the name and version of your compiler,
884
  * the complete command line flags you give to your compiler,
885
  * the complete compiler error messages (if the question is about compilation),
886
  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.