2013-03-23 14 views
5

Ho una funzione C uint8_t command_read(const FILE* const in) che legge da in. Mi piacerebbe scrivere un test unitario per la funzione. È possibile creare un FILE* in memoria per il test poiché vorrei evitare di dover interagire con il filesystem? In caso contrario, quali sono le alternative?Come testare una funzione C con un argomento FILE *

risposta

9

È possibile creare un FILE * in memoria per il test?

Sicuro. Per scrivere:

char *buf; 
size_t sz; 
FILE *f = open_memstream(&buf, &sz); 

// do stuff with `f` 

fclose(f); 
// here you can access the contents of `f` using `buf` and `sz` 

free(buf); // when done 

Questo è POSIX. Docs.

Per la lettura:

char buf[] = "Hello world! This is not a file, it just pretends to be one."; 
FILE *f = fmemopen(buf, sizeof(buf), "r"); 
// read from `f`, then 
fclose(f); 

This is POSIX too.

Nota a margine:

vorrei evitare il test di dover interagire con il file system.

Perché?

+2

"* Perché? *" - questa è la natura del collaudo dell'unità. Vuoi testare ** la funzionalità del modulo ** senza il coinvolgimento di fattori esterni. Ecco perché le interfacce esterne sono solitamente emulate da stub o qualcosa del genere. – SomeWittyUsername

+1

@icepack Euh, non è irrealistico? Voglio dire, se c'è un errore nell'aprire un file, eppure il test dell'unità passa ... –

+0

L'UT deve iniettare tutti i possibili tipi di input nel modulo controllato. L'apertura del file non riuscita viene facilmente emulata fornendo un gestore NULL alla funzione. Il comportamento previsto dovrebbe essere restituito con errore o asserire. – SomeWittyUsername

Problemi correlati