De vez en cuando en el trabajo, intentan obligarnos a escribir pruebas unitarias. Muchos ya se han dado cuenta de que hacen un daño. Escribir exámenes lleva mucho tiempo, por lo que podrías hacer algo más útil. Si la prueba comienza a caer inesperadamente, el ensamblaje se descompone en el servidor de integración continua, el lanzamiento no se implementa a tiempo, el negocio pierde dinero y usted, el autor de la prueba de la unidad caída, termina en el extremo. Al refactorizar, las pruebas causan dolor de cabeza porque comienzan a caer y usted tiene que lidiar con eso.
Sin embargo, los jefes malvados requieren más pruebas, hablando sobre el llamado "control de calidad". Los gerentes particularmente astutos incluso consideran la cobertura y no te dejan ir a trabajar hasta que se logra. Su código está envuelto en una revisión si no hay pruebas en él o si no les gustó algo. Completamente molesto!
Que hacer
Afortunadamente, hay formas de escribir pruebas unitarias confiables que nunca fallan. Estos métodos no fueron inventados por mí; se practican con éxito en varios proyectos de código abierto. Todos los ejemplos que daré están tomados del código real. Por lo tanto, no hay razón y no puede aprovechar lo que otros desarrolladores ya están poniendo en práctica.
La primera y obvia manera: no verifique nada en la prueba de la unidad. Aquí hay un ejemplo simple :
public void testSetFile() {
System.out.println("setFile");
File f = null;
BlastXMLParser instance = new BlastXMLParser();
instance.setFile(f);
}
? , , . - , null null'. , .
? :
@Test
public void getParametersTest() {
List<IGeneratorParameter<?>> parameters = generator.getParameters();
containsParameterType(parameters, AtomColor.class);
containsParameterType(parameters, AtomColorer.class);
containsParameterType(parameters, AtomRadius.class);
containsParameterType(parameters, ColorByType.class);
...
}
, - . containsParameterType:
public <T> boolean containsParameterType(List<IGeneratorParameter<?>> list, Class<T> type) {
for (IGeneratorParameter<?> item : list) {
if (item.getClass().getName().equals(type.getName())) return true;
}
return false;
}
, ? , . , . !
. , . - . , , , . :
for (int i = 0; i < 0; i++)
{
Assert.assertTrue(errorProbabilities[i] > 0.0d);
}
0 . . :
List<JavaOperationSignature> sigs = new ArrayList<>();
List<JavaOperationSignature> sigs2 = new ArrayList<>();
for (int i = 0; i < sigs.size(); i++) {
sigs.add(JavaOperationSignature.buildFor(nodes.get(i)));
sigs2.add(JavaOperationSignature.buildFor(nodes2.get(i)));
}
for (int i = 0; i < sigs.size() - 1; i++) {
assertTrue(sigs.get(i) == sigs.get(i + 1));
assertTrue(sigs2.get(i) == sigs2.get(i + 1));
}
! , — . .
, , , . , catch. , . , :
try {
getDs().save(e);
} catch (Exception ex) {
return;
}
Assert.assertFalse("Should have got rejection for dot in field names", true);
e = getDs().get(e);
Assert.assertEquals("a", e.mymap.get("a.b"));
Assert.assertEquals("b", e.mymap.get("c.e.g"));
, ? ? , . , . , null:
Assert.assertNotNull(new Electronegativity());
new
null, . . , , . — :
DocumentImplementation document = new DocumentImplementation(props);
assertNotNull(document.toString().contains(KEY));
assertNotNull(document.toString().contains(VALUE));
boolean
Boolean
, , , . , , true false. :
Assert.assertNotNull("could not get nr. of eqr: ", afpChain.getNrEQR());
. , , getNrEQR
int
.
— , :
Assert.assertNotNull("Attempt to test atom type which is not defined in the " +
getAtomTypeListName() + ": " + exception.getMessage());
? , - , - . , null, , .
, , , assertNotNull
. ! , assertEquals
, :
Assert.assertEquals(ac2.getAtomCount(), ac2.getAtomCount());
, , getAtomCount
. - !
double, NaN. , assertNotEquals
, . assertTrue
:
Assert.assertTrue(result1.get(i) != Double.NaN);
, NaN , , .
assertTrue
instanceof-:
Assert.assertNotNull(cf.getRealFormat());
Assert.assertNotNull(cf.getImaginaryFormat());
Assert.assertTrue(cf.getRealFormat() instanceof NumberFormat);
Assert.assertTrue(cf.getImaginaryFormat() instanceof NumberFormat);
getRealFormat
getImaginaryFormat
NumberFormat
, instanceof . . .
, . , assertThat
AssertJ (, assertThat(somethingIsTrue())
assertThat(somethingIsTrue()).is(true)
). try { ... } catch(Throwable t) {}
AssertionError
. . , CompletableFuture.runAsync()
. , , .
. . . , , . ---!