Add unit test file test_stack.c
This commit is contained in:
parent
d51184f13b
commit
833e93fa49
109
test_stack.c
109
test_stack.c
@ -0,0 +1,109 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include "stack.h"
|
||||
|
||||
// Hilfsfunktion: beendet Programm bei malloc-Fehler
|
||||
int *make_int(int value)
|
||||
{
|
||||
int *p = malloc(sizeof(int));
|
||||
assert(p != NULL);
|
||||
*p = value;
|
||||
return p;
|
||||
}
|
||||
|
||||
// Test: Push und Top.
|
||||
void test_push_and_top()
|
||||
{
|
||||
printf("Running test_push_and_top...\n");
|
||||
|
||||
StackNode *stack = NULL;
|
||||
|
||||
int *a = make_int(10);
|
||||
int *b = make_int(20);
|
||||
|
||||
stack = push(stack, a);
|
||||
stack = push(stack, b);
|
||||
|
||||
int *topValue = (int *)top(stack);
|
||||
assert(topValue != NULL);
|
||||
assert(*topValue == 20);
|
||||
|
||||
clearStack(stack);
|
||||
free(a);
|
||||
free(b);
|
||||
|
||||
printf(" test_push_and_top passed\n");
|
||||
}
|
||||
|
||||
// Test: Pop in korrekter Reihenfolge
|
||||
void test_push_pop_sequence()
|
||||
{
|
||||
printf("Running test_push_pop_sequence...\n");
|
||||
|
||||
StackNode *stack = NULL;
|
||||
|
||||
int *a = make_int(1);
|
||||
int *b = make_int(2);
|
||||
int *c = make_int(3);
|
||||
|
||||
stack = push(stack, a);
|
||||
stack = push(stack, b);
|
||||
stack = push(stack, c);
|
||||
|
||||
// Pop 3
|
||||
int *v = (int *)top(stack);
|
||||
assert(*v == 3);
|
||||
stack = pop(stack);
|
||||
|
||||
// Pop 2
|
||||
v = (int *)top(stack);
|
||||
assert(*v == 2);
|
||||
stack = pop(stack);
|
||||
|
||||
// Pop 1
|
||||
v = (int *)top(stack);
|
||||
assert(*v == 1);
|
||||
stack = pop(stack);
|
||||
|
||||
// Stack sollte leer sein
|
||||
assert(stack == NULL);
|
||||
|
||||
free(a);
|
||||
free(b);
|
||||
free(c);
|
||||
|
||||
printf(" test_push_pop_sequence passed\n");
|
||||
}
|
||||
|
||||
// Test: clearStack
|
||||
void test_clearStack()
|
||||
{
|
||||
printf("Running test_clearStack...\n");
|
||||
|
||||
StackNode *stack = NULL;
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
stack = push(stack, make_int(i));
|
||||
|
||||
clearStack(stack);
|
||||
|
||||
// danach ist Stack nur als "gelöscht" markiert,
|
||||
// aber Pointer ist nicht automatisch NULL → das prüft man so:
|
||||
stack = NULL;
|
||||
|
||||
printf(" test_clearStack passed\n");
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
printf("=== Running Stack Unit Tests ===\n");
|
||||
|
||||
test_push_and_top();
|
||||
test_push_pop_sequence();
|
||||
test_clearStack();
|
||||
|
||||
printf("=== All tests passed successfully! ===\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user