Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JUNIT - multiple tests with String

I try to realize unit tests by respecting best practices. One of the rules is to use only one "assert" by method. I would like realize several tests by method because there is a heavy treatment which is made at the beginning of every method (insertion in database - > 5 seconds).

I developed this solution, is it a good practice?

String failuresMsg = "";
if(9 != var1) 
    failuresMsg += "[var1 <9," + var1+">]";
if(9 != var2) 
    failuresMsg += "[var2 <9," + var2+">]";
if(9 != var3) 
    failuresMsg += "[var3 <9," + var3+">]";
if(9 != var4) 
    failuresMsg += "[var4 <9," + var4+">]";

assertEquals("", failuresMsg);
like image 707
Martinus Paladinus Avatar asked Sep 21 '26 22:09

Martinus Paladinus


1 Answers

One of the rules is to use only one "assert" by method.

No you should limit yourself to test a scenario by method of test. It is not the same thing.

String failuresMsg = "";
if(9 != var1) 
    failuresMsg += "[var1 <9," + var1+">]";
if(9 != var2) 
    failuresMsg += "[var2 <9," + var2+">]";
if(9 != var3) 
    failuresMsg += "[var3 <9," + var3+">]";
if(9 != var4) 
    failuresMsg += "[var4 <9," + var4+">]";

assertEquals("", failuresMsg);

Generally, when you have values acceptable according to a range, you should at least test the limits of this range and one or several inner values of the range.

If if take your test, it would give 2 methods of tests (or more according to the way of seeing things) because I have two distinct scenarios :

  • the value is acceptable

  • the value is not acceptable

For each scenario, I may perform any assertions that I need if the code and the maintainability of tests stay good.

Here is a sample code :

@Test
public void doMethodWithAcceptableValues(){
   int testValue = 0;
   Assert.assertTrue(objUnderTest.doMethod(testValue));
   testValue = 100; // limit value
   Assert.assertTrue(objUnderTest.doMethod(testValue));
   testValue = 50; // middle value 50. it is an example
   Assert.assertTrue(objUnderTest.doMethod(testValue));
}

@Test
public void doMethodWithNotAcceptableValues(){
   int testValue = -1;
   Assert.assertFalse("-1 not acceptable", objUnderTest.doMethod(testValue));
   testValue = 101; // limit value
   Assert.assertFalse("101 not acceptable", objUnderTest.doMethod(testValue));
}

Nothing prevents you from testing all values of the interval if the interval is not too much important, you could use JUnit mechanisms for it (Parameterized tests) or create your own method which perform this logic with a loop for example.
In many cases, home processing is more simple, readable and maintainable.

like image 81
davidxxx Avatar answered Sep 23 '26 12:09

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!