Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to calculate the expected_value in assertEquals() method in jUnit

I'm using the assertEquals() method in jUnit to test a certain value is equals or not to the actual value the code generates.

/*
  calculating the actual_value
*/
int expected_value = 1000; // rows of the set of files, manually calculated
assertEquals(expected_value, actual_value);

I'm wondering if I do it something like below will that be a problem, in case of standards and formalities.

/*
  calculating the actual_value
*/
int expected_value = getRelevantLinesOfFiles(set of files); // rows of the set of files
assertEquals(expected_value, actual_value);

since it's almost impossible to always find that kind of variable manually, I've written a method to read and calculate the relevant lines in those files.

My concern is that I'm using an out put of a method in assertEquals testing. But the getRelevantLinesOfFiles() method is not tested. If I'm going to test it, then again i have to manually read the files. So it's kinda same thing again and again.

Is that a good practice ? or what is the best way to do these kind of testing ?

like image 524
prime Avatar asked Oct 31 '22 21:10

prime


1 Answers

If those files are also the input that actual_value is calculated from, what you're doing is testing an alternative implementation vs the real one. That's valid but requires understanding things up front, e.g it's usually done with a very simple and easy-to-review test implementation compared with an optimized and more complicated 'production' implementation. If that's not the case you're doing something wrong.

If the files contain results that actual_value isn't calculated from then it should be ok, e.g if you have sets of inputs and matching sets of expected output.

Also, consider whether you can distill at least a few cases of trivial hard-coded input and hard-coded expected output, similar to your first example, not involving files. This may require allowing your interface to work with an abstraction that isn't a File in order to mock input, or to be able to inject an alternative file-reading mechanism in tests that actually serves mock test data.

EDIT: just to provide a concrete example of a great abstraction to use instead of File instances (or filenames, or whatever) consider using okio and passing in a set of Source instances.

Real implementation: given a list of File instances, create Source instances using Okio.source(file).

Tests: pass a list of Buffer instances containing whatever you want

Buffer b = new Buffer();
b.writeUtf8("whatever the hell I want in this file");
// can also write bytes or anything else

int actualValue = getRelevantLinesOfFiles(Arrays.asList(b));
like image 59
orip Avatar answered Nov 15 '22 06:11

orip