Synthèse automatique
Décrit la forme imposée des tests unitaires JUnit Jupiter/Mockito de ce dépôt : ordre des champs mock, phases given/when/then nommées et vérifications avec valeurs réelles.
Points forts
- Donne un modèle de référence complet et copiable (ControllerTest.java) plutôt que des règles abstraites
- Fixe un ordre de champs en trois groupes avec la justification de chaque groupe
- Explique quand @InjectMocks ne suffit pas et fournit l'alternative avec @BeforeEach
- Délimite clairement son périmètre : uniquement les *Test.java, pas les *IT.java sous failsafe
Limites
- Fortement lié au dépôt registryatlas et à ses classes (Controller, Service, CompanyProfile), donc peu réutilisable tel quel ailleurs
- Le texte s'interrompt au milieu de la règle sur le repliement des phases given/when, laissant la consigne incomplète
- Ne couvre pas les assertions au-delà d'assertEquals ni les cas de tests paramétrés
À charger avant d'écrire ou de modifier un fichier *Test.java dans ce dépôt afin de respecter la structure Mockito/JUnit maison.
Pour les tests d'intégration *IT.java sous failsafe/Testcontainers ou pour un projet Java qui n'applique pas cette convention.
Analyse de sécurité
SûrPure editorial style guide for writing JUnit Jupiter/Mockito tests. It contains no commands, no network or shell instructions, no file-system operations, no credential handling, and no attempt to disable agent safety behavior — only prose conventions and Java code samples. The one literal string ("api-key") is an obvious placeholder in an illustrative snippet, not a real secret.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Write a ControllerTest for the new getCompanyById endpoint, following the repo's unit test pattern.This test file has a blank line between every @Mock field — reorder the fields and regroup them per the unit-test-pattern skill.Service now takes an API key string in its constructor; rewrite ServiceTest so it still follows the unit test pattern.name: unit-test-pattern description: Sam's shape for JUnit Jupiter and Mockito unit tests — mock field ordering, given/when/then phases, matchers in when() and real values in verify(). Load before writing or editing any *Test.java in this repo.
Unit test pattern
Every unit test in this repo copies the shape of ControllerTest.java. JUnit Jupiter for assertions,
Mockito for collaborators, three named phases, one mock field block in a fixed order.
This skill governs *Test.java only. *IT.java runs under failsafe against Testcontainers and is a
different animal — nothing here applies to it.
The reference test
src/test/java/io/github/samrjthompson/registryatlas/companies/api/ControllerTest.java:
@ExtendWith(MockitoExtension.class)
public class ControllerTest {
@Mock
private Service service;
@InjectMocks
private Controller controller;
@Test
void shouldRetrieveCompaniesWithinFiveMileRadiusOfPostcode() {
// given
final String postcode = "G12 8AU";
final long radius = 5L;
when(service.getCompanies(anyString(), anyLong())).thenReturn(List.of());
// when
final ResponseEntity<List<String>> actual = controller.getCompanies(postcode, radius);
// then
assertEquals(HttpStatusCode.valueOf(HttpStatus.OK.value()), actual.getStatusCode());
assertEquals(List.of(), actual.getBody());
verify(service).getCompanies(postcode, radius);
}
}
Field ordering
Three groups in this order, separated by a single blank line. Never put a blank line inside a group.
@Mock
private Service service;
@Mock
private Repository repository;
@InjectMocks
private Controller controller;
@Mock
private CompanyProfile companyProfile;
- Constructor dependencies of the class under test.
- The class under test.
- General mocks — every mock that is not a constructor dependency: a mocked argument passed to the method under test, or a mocked object a stub hands back.
Not this — a blank line between every @Mock loses the grouping the layout exists to show:
@Mock
private Service service;
@Mock
private Repository repository;
@InjectMocks
private Controller controller;
@Mock
private CompanyProfile companyProfile;
Constants go above all three groups, as in any Java class.
The grouping is for the reader. @InjectMocks injects by type and ignores field position, so a general
mock whose type happens to match a constructor parameter is still injected — position does not prevent
it.
When @InjectMocks will not do
If the constructor takes a String or another plain value Mockito cannot supply, drop @InjectMocks.
Declare the field bare in the same middle position and build it in @BeforeEach void setUp(). The real
dependencies keep their @Mock:
@ExtendWith(MockitoExtension.class)
public class ServiceTest {
private static final String API_KEY = "api-key";
@Mock
private Client client;
@Mock
private Repository repository;
private Service service;
@Mock
private CompanyProfile companyProfile;
@BeforeEach
void setUp() {
service = new Service(client, repository, API_KEY);
}
}
The three phases
Every test body is // given, // when, // then, each marker preceded by a blank line. This is the
normal case, and most tests look exactly like it.
These markers are the sole exception to the no-code-comments skill. They mark structure rather than
explain code, so they cannot rot. Nothing else in a test file may carry a comment — if a step needs
explaining, rename the variable or the test method until it does not.
Folding two phases together
Where a phase would stand completely empty, fold it into its neighbour and combine the two markers.
Fold given into when only when there is nothing whatever to arrange — the method under test takes no
arguments, or takes only mocks already declared at class level. Declaring a local is arranging, so a
test carrying even one final String postcode = "G12 8AU"; keeps its own // given:
@Test
void shouldPassSuppliedCompanyToService() {
// given / when
controller.save(companyProfile);
// then
verify(service).save(companyProfile);
}
Fold when into then when the call under test happens inside the assertion, leaving no separate
invocation to mark:
@Test
void shouldPropagateExceptionWhenPostcodeIsUnknown() {
// given
final String postcode = "ZZ99 9ZZ";
final long radius = 5L;
when(service.getCompanies(anyString(), anyLong())).thenThrow(new PostcodeNotFoundException());
// when / then
assertThrows(PostcodeNotFoundException.class, () -> controller.getCompanies(postcode, radius));
}
assertDoesNotThrow(() -> controller.getCompanies()) folds the same way.
Three separate markers stay the default. Reach for a combined marker because the test came out that shape, not to tighten a test that already reads fine.
Stubbing and verification
Real values never appear inside when(). They appear in the verify(…) arguments in the then step,
which is what pins the contract:
// given
final String postcode = "G12 8AU";
final long radius = 5L;
when(service.getCompanies(anyString(), anyLong())).thenReturn(List.of());
// then
verify(service).getCompanies(postcode, radius);
Never when(service.getCompanies("G12 8AU", 5L)).
Reach for the type-specific matcher first — anyString(), anyLong(), anyInt(), anyList(). Use
any(Foo.class) or eq(Foo.class) only where the extra specificity is genuinely required, such as
picking between overloads or matching a class-literal argument:
when(restClient.get(anyString(), eq(CompanyProfile.class))).thenReturn(companyProfile);
Mockito is all-or-nothing about matchers: once one argument is a matcher, every argument must be. That
is the only reason eq() exists — not as a way to smuggle a real value into a stub.
Assertions
JUnit Jupiter only, statically imported from org.junit.jupiter.api.Assertions — assertEquals,
assertThrows, assertTrue, and the rest. AssertJ and Hamcrest are not on the classpath and adding
either needs Sam's agreement first.
Static imports throughout: assertEquals, not Assertions.assertEquals; when and verify, not
Mockito.when and Mockito.verify.
Naming and modifiers
- Class is
public, named<ClassUnderTest>Test, annotated@ExtendWith(MockitoExtension.class). - Test methods are package-private and
void. Nopublic. - Method names start
shouldand carry both the behaviour and the condition:shouldRetrieveCompaniesWithinFiveMileRadiusOfPostcode, nottestGetCompanies. - Locals are
final. - The result of the call under test is named
actual.
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/junit-mockito-unit-test-pattern-msr1u7k2/download' --output '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md.part' && mv '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md.part' '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md' && test -s '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/unit-test-pattern' && cp -R '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2' '.claude/skills/unit-test-pattern'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2'openskills read 'junit-mockito-unit-test-pattern-msr1u7k2'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Comparaison de performances ClickHouse
Testing
Évaluez les résultats de tests de performance ClickHouse, analysez les régressions de PR, comparez avec l'historique et vérifiez la fiabilité des mesures.
Analyse des rapports de performance CI
Testing
Analyse les rapports de comparaison de performance CI pour une PR ClickHouse. Recoupe l'historique master pour distinguer les vraies régressions des tests instables.
Méthode Santa
Testing
Vérification adversarial multi-agents avec deux réviseurs indépendants. La sortie est vérifiée deux fois et corrigée itérativement jusqu'à ce que les deux acceptent avant publication.