Nantes Université

Skip to content
Extraits de code Groupes Projets
Valider 58777baa rédigé par Reda ESSEKKAKI's avatar Reda ESSEKKAKI
Parcourir les fichiers

introduction of Invariant Assertions and test

parent 15159a85
Branches
Aucune étiquette associée trouvée
1 requête de fusion!2Implementation of Assertions in commons-assertions module.
......@@ -5,6 +5,7 @@ import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.io.File;
import java.util.function.Predicate;
/**
* The Assertion class provides a set of methods for performing assertions on various types of values.
......@@ -37,6 +38,8 @@ public class Assertion implements AssertionInterface {
*/
static final String PATTERNFALSE = "\nExpecting value (%s) not to be %s (%s)";
public static boolean isActive;
/**
......@@ -50,7 +53,6 @@ public class Assertion implements AssertionInterface {
if (isActive)
assertions.put(Thread.currentThread(), this);
}
/**
* Returns the current Assertion object associated with the current thread.
*/
......@@ -197,4 +199,18 @@ public class Assertion implements AssertionInterface {
return assertion().message();
}
public interface Invariant<T> {
boolean test(T obj);
}
public static <T> void checkInvariant(T obj, Invariant<T> inv, String message) {
if (!inv.test(obj)) {
throw new IllegalStateException(message);
}
}
public static <T> Invariant<T> createInv(Predicate<T> predicate) {
return obj -> predicate.test(obj);
}
}
\ No newline at end of file
package org.atlanmod.commons.assertions;
import org.junit.jupiter.api.Test;
public class InvariantAssertionTest {
public class Person {
public int age;
public Person(int age) {
this.age = age;
Assertion.Invariant<Person> inv = Assertion.createInv(p -> p.age > 0);
Assertion.checkInvariant(this, inv, "Age must be positive");
}
public void setAge(int age) {
Assertion.Invariant<Person> inv = Assertion.createInv(p -> age > 0);
Assertion.checkInvariant(this, inv, "Age must be positive");
this.age = age;
}
public int getAge(){
return this.age;
}
}
Person p1 = new Person(15);
@Test
void testInvariantTrue(){
Assertion.Invariant i;
i = Assertion.createInv((Person p1) -> {
boolean b = p1.age == 15;
return b;
});
Assertion.checkInvariant(p1,i,i.toString());
}
}
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Veuillez vous inscrire ou vous pour commenter