/src/example/customer_database_test.c

http://cmockery.googlecode.com/ · C · 69 lines · 42 code · 7 blank · 20 comment · 0 complexity · d4884355c25a307b7e18cbb1f7ae0383 MD5 · raw file

  1. /*
  2. * Copyright 2008 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <stdarg.h>
  17. #include <stddef.h>
  18. #include <setjmp.h>
  19. #include <cmockery.h>
  20. #include <database.h>
  21. extern DatabaseConnection* connect_to_customer_database();
  22. extern unsigned int get_customer_id_by_name(
  23. DatabaseConnection * const connection, const char * const customer_name);
  24. // Mock query database function.
  25. unsigned int mock_query_database(
  26. DatabaseConnection* const connection, const char * const query_string,
  27. void *** const results) {
  28. *results = (void**)((unsigned)mock());
  29. return (unsigned int)mock();
  30. }
  31. // Mock of the connect to database function.
  32. DatabaseConnection* connect_to_database(const char * const database_url,
  33. const unsigned int port) {
  34. return (DatabaseConnection*)((unsigned)mock());
  35. }
  36. void test_connect_to_customer_database(void **state) {
  37. will_return(connect_to_database, 0x0DA7ABA53);
  38. assert_int_equal((int)connect_to_customer_database(), 0x0DA7ABA53);
  39. }
  40. /* This test fails as the mock function connect_to_database() will have no
  41. * value to return. */
  42. void fail_connect_to_customer_database(void **state) {
  43. assert_true(connect_to_customer_database() ==
  44. (DatabaseConnection*)0x0DA7ABA53);
  45. }
  46. void test_get_customer_id_by_name(void **state) {
  47. DatabaseConnection connection = {
  48. "somedatabase.somewhere.com", 12345678, mock_query_database
  49. };
  50. // Return a single customer ID when mock_query_database() is called.
  51. int customer_ids = 543;
  52. will_return(mock_query_database, &customer_ids);
  53. will_return(mock_query_database, 1);
  54. assert_int_equal(get_customer_id_by_name(&connection, "john doe"), 543);
  55. }
  56. int main(int argc, char* argv[]) {
  57. const UnitTest tests[] = {
  58. unit_test(test_connect_to_customer_database),
  59. unit_test(test_get_customer_id_by_name),
  60. };
  61. return run_tests(tests);
  62. }