diff --git a/README.md b/README.md index b8f6951..8782da8 100644 --- a/README.md +++ b/README.md @@ -448,6 +448,7 @@ Quarkus lets imperative (blocking, Panache-based) and reactive (Mutiny-based) co - Every endpoint returns an `ApiResponse` (or `ApiResponse>` for lists) - Permission checks are always declarative (`@PermissionsAllowed("RESOURCE:ACTION")` on the resource method), never a manual `if` inside a method body - No JAX-RS resource method contains business logic - it validates via Bean Validation annotations on the request DTO, delegates to a service, and maps the result to an `ApiResponse` +- **Test naming convention**: every test method is named `_NN_Should_When`, where `NN` is a two-digit sequence number with a leading zero, restarting at `_01_` in each test class and following the order of the methods in the source (e.g. `_01_ShouldReturnCategory_WhenCategoryExists`, `_02_ShouldReturnEmpty_WhenCategoryDoesNotExist`). This applies to every kind of test (unit, repository, resource, integration, parameterized). No other style (`shouldX()`, `testX()`, `givenX_whenY_thenZ()`) is accepted. ## Concepts covered diff --git a/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java b/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java index 5ddb7d2..e96d33e 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java @@ -15,7 +15,7 @@ class ApiResponseTest { @Test - void successBuildsEnvelopeWithFlagMessageDataAndTimestamp() { + void _01_ShouldBuildEnvelopeWithAllFields_WhenCreatedWithSuccess() { Instant before = Instant.now(); ApiResponse response = ApiResponse.success("payload", "done"); Instant after = Instant.now(); @@ -29,7 +29,7 @@ void successBuildsEnvelopeWithFlagMessageDataAndTimestamp() { } @Test - void successAcceptsNullData() { + void _02_ShouldAcceptNullData_WhenCreatedWithSuccess() { ApiResponse response = ApiResponse.success(null, "empty"); assertTrue(response.success()); assertNull(response.data()); diff --git a/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java b/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java index 62ec98c..90a7609 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java @@ -15,19 +15,19 @@ class PageResponseTest { @Test - void totalPagesUsesCeilingDivision() { + void _01_ShouldUseCeilingDivision_WhenComputingTotalPages() { assertEquals(3, PageResponse.of(List.of(1, 2, 3), 0, 3, 7).totalPages()); assertEquals(2, PageResponse.of(List.of(1, 2, 3), 0, 3, 6).totalPages()); assertEquals(1, PageResponse.of(List.of(1), 0, 10, 1).totalPages()); } @Test - void sizeZeroYieldsZeroPagesWithoutDividingByZero() { + void _02_ShouldYieldZeroPages_WhenSizeIsZero() { assertEquals(0, PageResponse.of(List.of(), 0, 0, 5).totalPages()); } @Test - void emptyContentYieldsZeroPages() { + void _03_ShouldYieldZeroPages_WhenContentIsEmpty() { PageResponse page = PageResponse.of(List.of(), 0, 10, 0); assertEquals(0, page.totalPages()); assertTrue(page.content().isEmpty()); @@ -35,7 +35,7 @@ void emptyContentYieldsZeroPages() { } @Test - void keepsPassedValues() { + void _04_ShouldKeepPassedValues_WhenBuilt() { PageResponse page = PageResponse.of(List.of(4, 5), 2, 2, 6); assertEquals(2, page.page()); assertEquals(2, page.size()); diff --git a/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java b/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java index e544d7a..a4ccf4e 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java @@ -22,7 +22,7 @@ class ProblemDetailsTest { private static final String PROBLEM_JSON = "application/problem+json"; @Test - void resourceNotFoundIsProblem404() { + void _01_ShouldReturnProblem404_WhenResourceNotFound() { given().when().get("/test-support/not-found") .then().statusCode(404) .contentType(PROBLEM_JSON) @@ -34,7 +34,7 @@ void resourceNotFoundIsProblem404() { } @Test - void businessRuleIsProblem422() { + void _02_ShouldReturnProblem422_WhenBusinessRuleViolated() { given().when().get("/test-support/business-rule") .then().statusCode(422) .contentType(PROBLEM_JSON) @@ -46,7 +46,7 @@ void businessRuleIsProblem422() { } @Test - void beanValidationFailureIsProblem400WithViolations() { + void _03_ShouldReturnProblem400WithViolations_WhenBeanValidationFails() { given().contentType("application/json").body("{\"name\":\"\"}") .when().post("/test-support/validate") .then().statusCode(400) @@ -57,7 +57,7 @@ void beanValidationFailureIsProblem400WithViolations() { } @Test - void validRequestStillReturnsSuccessEnvelope() { + void _04_ShouldReturnSuccessEnvelope_WhenRequestIsValid() { given().contentType("application/json").body("{\"name\":\"bob\"}") .when().post("/test-support/validate") .then().statusCode(200) @@ -66,7 +66,7 @@ void validRequestStillReturnsSuccessEnvelope() { } @Test - void unexpectedExceptionIsGeneric500WithoutLeaks() { + void _05_ShouldReturnGeneric500WithoutLeaks_WhenUnexpectedExceptionThrown() { String body = given().when().get("/test-support/unexpected") .then().statusCode(500) .contentType(PROBLEM_JSON) diff --git a/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java b/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java index d86cf66..ced2272 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java @@ -34,7 +34,7 @@ class FlywaySchemaTest { DataSource dataSource; @Test - void allExpectedTablesExistInPublicSchema() throws SQLException { + void _01_ShouldCreateAllExpectedTables_WhenMigrationsRun() throws SQLException { Set tables = new HashSet<>(); try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement( @@ -48,7 +48,7 @@ void allExpectedTablesExistInPublicSchema() throws SQLException { } @Test - void schemaHistoryShowsVersionOneSuccess() throws SQLException { + void _02_ShouldRecordVersionOneAsSuccess_WhenMigrationsRun() throws SQLException { try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement( "SELECT success FROM flyway_schema_history WHERE version = '1'"); @@ -59,7 +59,7 @@ void schemaHistoryShowsVersionOneSuccess() throws SQLException { } @Test - void duplicateUserEmailIsRejectedByTheDatabase() throws SQLException { + void _03_ShouldRejectInsert_WhenUserEmailIsDuplicated() throws SQLException { String sql = "INSERT INTO users (first_name, last_name, email, password) VALUES ('A', 'B', ?, 'x')"; String email = "dup-" + System.nanoTime() + "@example.com"; try (Connection c = dataSource.getConnection()) { diff --git a/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java b/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java index 5ac686e..0d3e20a 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java @@ -19,7 +19,7 @@ class HealthEndpointsTest { @Test - void readinessIsUpAndReportsDatabaseCheck() { + void _01_ShouldReportUpWithDatabaseCheck_WhenReadinessQueried() { given().when().get("/q/health/ready") .then().statusCode(200) .body("status", is("UP")) @@ -27,7 +27,7 @@ void readinessIsUpAndReportsDatabaseCheck() { } @Test - void livenessIsUpAndReportsApplicationCheck() { + void _02_ShouldReportUpWithApplicationCheck_WhenLivenessQueried() { given().when().get("/q/health/live") .then().statusCode(200) .body("status", is("UP")) diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java index 3cb6f9c..6b6a112 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java @@ -56,7 +56,7 @@ private Long persist(String name) { } @Test - void persistAndFind() { + void _01_ShouldFindCategory_WhenPersisted() { categoryId = persist("Repo test"); Category found = QuarkusTransaction.requiringNew().call(() -> repository.findById(categoryId)); assertNotNull(found); @@ -64,7 +64,7 @@ void persistAndFind() { } @Test - void countProductsReflectsInsertedRows() { + void _02_ShouldCountInsertedProducts_WhenProductsAdded() { categoryId = persist("Repo count"); assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> productRepository.countByCategoryId(categoryId))); diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java index 35b59fd..ede6ec9 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java @@ -53,7 +53,7 @@ private Long persist(String telephone, String email, String address) { } @Test - void persistAndFindRoundTrip() { + void _01_ShouldRoundTripCustomer_WhenPersistedAndFound() { customerId = persist("123", "ada@example.com", "London"); Customer found = QuarkusTransaction.requiringNew().call(() -> repository.findById(customerId)); assertNotNull(found); @@ -65,7 +65,7 @@ void persistAndFindRoundTrip() { } @Test - void nullableColumnsRoundTripAsNull() { + void _02_ShouldRoundTripNulls_WhenOptionalColumnsAreNull() { customerId = persist(null, null, null); Customer found = QuarkusTransaction.requiringNew().call(() -> repository.findById(customerId)); assertNotNull(found); @@ -75,7 +75,7 @@ void nullableColumnsRoundTripAsNull() { } @Test - void deleteRemovesRow() { + void _03_ShouldRemoveRow_WhenCustomerDeleted() { customerId = persist(null, null, null); QuarkusTransaction.requiringNew().run(() -> repository.deleteById(customerId)); assertNull(QuarkusTransaction.requiringNew().call(() -> repository.findById(customerId))); diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java index f0410ab..97b51eb 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java @@ -116,7 +116,7 @@ private List ids(Long customerId, Long productId) { } @Test - void persistAndFindRoundTripOnTheCustomerOrderEntity() { + void _01_ShouldRoundTripOrder_WhenPersistedAndFound() { Long id = order(customerA, productA, 3, "7.50"); Order found = QuarkusTransaction.requiringNew().call(() -> { @@ -132,7 +132,7 @@ void persistAndFindRoundTripOnTheCustomerOrderEntity() { } @Test - void searchAndCountWorkWithEveryFilterCombination() { + void _02_ShouldSearchAndCount_WhenAnyFilterCombinationUsed() { Long o1 = order(customerA, productA, 1, "2.50"); Long o2 = order(customerA, productB, 2, "5.00"); Long o3 = order(customerB, productA, 3, "7.50"); @@ -156,7 +156,7 @@ void searchAndCountWorkWithEveryFilterCombination() { } @Test - void countByCustomerAndProductCountOnlyReferencingOrders() { + void _03_ShouldCountOnlyReferencingOrders_WhenCountingByCustomerAndProduct() { order(customerA, productA, 1, "2.50"); order(customerA, productB, 1, "2.50"); order(customerB, productA, 1, "2.50"); @@ -170,7 +170,7 @@ void countByCustomerAndProductCountOnlyReferencingOrders() { } @Test - void foreignKeysAndChecksAreEnforced() { + void _04_ShouldEnforceForeignKeysAndChecks_WhenInvalidRowInserted() { assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em .createNativeQuery("insert into orders (customer_id, product_id, quantity, total) " + "values (999999999, " + productA + ", 1, 1.00)").executeUpdate())); diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java index e946429..b8d7cbe 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java @@ -71,7 +71,7 @@ private Long product(Long categoryId, String name, String price) { } @Test - void findByCategoryFiltersAndOrdersById() { + void _01_ShouldFilterAndOrderById_WhenFindingByCategory() { Long catA = category(); Long catB = category(); Long a1 = product(catA, "A1", "1.00"); @@ -92,7 +92,7 @@ void findByCategoryFiltersAndOrdersById() { } @Test - void countByCategoryIdCountsOnlyThatCategory() { + void _02_ShouldCountOnlyThatCategory_WhenCountingByCategoryId() { Long catA = category(); Long catB = category(); product(catA, "A1", "1.00"); @@ -105,7 +105,7 @@ void countByCategoryIdCountsOnlyThatCategory() { } @Test - void unitPriceRoundTripsAsNumeric12Scale2() { + void _03_ShouldRoundTripPriceAsNumeric12Scale2_WhenProductPersisted() { Long cat = category(); Long id = product(cat, "Precise", "79.99"); Long big = product(cat, "Big", "9999999999.99"); @@ -118,7 +118,7 @@ void unitPriceRoundTripsAsNumeric12Scale2() { } @Test - void missingCategoryViolatesForeignKey() { + void _04_ShouldViolateForeignKey_WhenCategoryMissing() { assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em .createNativeQuery("insert into products (category_id, product_name, unit_price) " + "values (999999999, 'Orphan', 1.00)").executeUpdate())); diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java index 4835524..0812ced 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java @@ -45,7 +45,7 @@ private User newUser(String email) { } @Test - void findByEmailIsCaseInsensitive() { + void _01_ShouldFindUser_WhenEmailCaseDiffers() { String email = "mixed" + System.nanoTime() + "@example.com"; QuarkusTransaction.requiringNew().run(() -> users.persist(newUser(email))); QuarkusTransaction.requiringNew().run(() -> { @@ -56,7 +56,7 @@ void findByEmailIsCaseInsensitive() { } @Test - void duplicateEmailViolatesUniqueConstraint() { + void _02_ShouldViolateUniqueConstraint_WhenEmailIsDuplicated() { String email = "dup" + System.nanoTime() + "@example.com"; QuarkusTransaction.requiringNew().run(() -> users.persist(newUser(email))); assertThrows(RuntimeException.class, @@ -67,7 +67,7 @@ void duplicateEmailViolatesUniqueConstraint() { } @Test - void tokenRepositoriesFindTheirRows() { + void _03_ShouldFindTheirRows_WhenTokensSaved() { long n = System.nanoTime(); String email = "tok" + n + "@example.com"; QuarkusTransaction.requiringNew().run(() -> { diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java index d9a8e7e..88a6e2a 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java @@ -70,7 +70,7 @@ void detachHandler() { } @Test - void fullFlowRegisterActivateLoginMeLogout() { + void _01_ShouldCompleteFullFlow_WhenRegisteringActivatingLoggingInAndOut() { String email = uniqueEmail(); register(email, PASSWORD).statusCode(201) .contentType("application/json") @@ -119,7 +119,7 @@ void fullFlowRegisterActivateLoginMeLogout() { } @Test - void forgotAndResetPasswordFlowIsSingleUse() { + void _02_ShouldAllowSingleUse_WhenResettingPassword() { String email = registerAndActivate(); given().contentType("application/json").body("{\"email\":\"" + email + "\"}") @@ -139,7 +139,7 @@ void forgotAndResetPasswordFlowIsSingleUse() { } @Test - void registerDuplicateEmailIs422() { + void _03_ShouldReturn422_WhenRegisteringDuplicateEmail() { String email = uniqueEmail(); register(email, PASSWORD).statusCode(201); register(email, PASSWORD).statusCode(422) @@ -149,7 +149,7 @@ void registerDuplicateEmailIs422() { } @Test - void registerWithInvalidBodyIs400WithViolations() { + void _04_ShouldReturn400WithViolations_WhenRegisterBodyInvalid() { given().contentType("application/json") .body("{\"firstName\":\"\",\"lastName\":\"L\",\"email\":\"not-an-email\",\"password\":\"short\"}") .when().post(BASE + "/register") @@ -161,7 +161,7 @@ void registerWithInvalidBodyIs400WithViolations() { } @Test - void loginUnknownEmailAndWrongPasswordAreIndistinguishable() { + void _05_ShouldBeIndistinguishable_WhenEmailUnknownOrPasswordWrong() { String email = registerAndActivate(); ValidatableResponse unknown = login(uniqueEmail(), PASSWORD).statusCode(401).contentType(PROBLEM_JSON); ValidatableResponse wrong = login(email, "WrongPassw0rd!!").statusCode(401).contentType(PROBLEM_JSON); @@ -171,7 +171,7 @@ void loginUnknownEmailAndWrongPasswordAreIndistinguishable() { } @Test - void loginBeforeActivationIs401() { + void _06_ShouldReturn401_WhenLoggingInBeforeActivation() { String email = uniqueEmail(); register(email, PASSWORD).statusCode(201); login(email, PASSWORD).statusCode(401) @@ -181,12 +181,12 @@ void loginBeforeActivationIs401() { } @Test - void meWithoutTokenIs401() { + void _07_ShouldReturn401_WhenCallingMeWithoutToken() { given().when().get(BASE + "/me").then().statusCode(401); } @Test - void activateWithBadTokenIs422() { + void _08_ShouldReturn422_WhenActivatingWithBadToken() { given().queryParam("token", "definitely-not-a-real-token").when().get(BASE + "/activate-account") .then().statusCode(422) .contentType(PROBLEM_JSON) diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java index 3e09a1f..bf8e2d1 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java @@ -83,7 +83,7 @@ private String tokenWith(String... permissions) { } @Test - void createReturns201WithEnvelope() { + void _01_ShouldReturn201WithEnvelope_WhenCreatingCategory() { String name = RbacTestSupport.unique("cat"); Long id = given().auth().oauth2(admin).contentType("application/json") .body("{\"categoryName\":\"" + name + "\"}").when().post(BASE) @@ -96,7 +96,7 @@ void createReturns201WithEnvelope() { } @Test - void getByIdAndUpdate() { + void _02_ShouldReturnAndUpdateCategory_WhenCategoryExists() { Long id = createViaApi(RbacTestSupport.unique("cat")); given().auth().oauth2(admin).when().get(BASE + "/" + id) .then().statusCode(200).body("success", is(true)).body("data.id", is(id.intValue())); @@ -108,7 +108,7 @@ void getByIdAndUpdate() { } @Test - void listIsPaginatedAndOrderedById() { + void _03_ShouldPaginateAndOrderById_WhenListingCategories() { Long a = createViaApi(RbacTestSupport.unique("cat")); Long b = createViaApi(RbacTestSupport.unique("cat")); Long c = createViaApi(RbacTestSupport.unique("cat")); @@ -127,13 +127,13 @@ void listIsPaginatedAndOrderedById() { } @Test - void invalidPageSizeIs400Problem() { + void _04_ShouldReturn400Problem_WhenPageSizeIsInvalid() { given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); } @Test - void unknownIdIs404Problem() { + void _05_ShouldReturn404Problem_WhenCategoryIdUnknown() { given().auth().oauth2(admin).when().get(BASE + "/999999999") .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) .body("$", not(hasKey("success"))); @@ -145,7 +145,7 @@ void unknownIdIs404Problem() { } @Test - void invalidBodyIs400ProblemWithViolations() { + void _06_ShouldReturn400ProblemWithViolations_WhenBodyInvalid() { String tooLong = "x".repeat(151); for (String body : List.of("{\"categoryName\":\" \"}", "{\"categoryName\":\"" + tooLong + "\"}")) { given().auth().oauth2(admin).contentType("application/json").body(body).when().post(BASE) @@ -161,7 +161,7 @@ void invalidBodyIs400ProblemWithViolations() { } @Test - void deleteRemovesCategory() { + void _07_ShouldRemoveCategory_WhenDeleteSucceeds() { Long id = createViaApi(RbacTestSupport.unique("cat")); given().auth().oauth2(admin).when().delete(BASE + "/" + id) .then().statusCode(200).body("success", is(true)); @@ -169,7 +169,7 @@ void deleteRemovesCategory() { } @Test - void deleteWithProductsIs422UntilProductRemoved() { + void _08_ShouldReturn422UntilProductRemoved_WhenCategoryHasProducts() { Long id = createViaApi(RbacTestSupport.unique("cat")); Long productId = insertProduct(id); given().auth().oauth2(admin).when().delete(BASE + "/" + id) @@ -183,7 +183,7 @@ void deleteWithProductsIs422UntilProductRemoved() { } @Test - void readOnlyUserCanReadButNotWrite() { + void _09_ShouldAllowReadButNotWrite_WhenCallerIsReadOnly() { Long id = createViaApi(RbacTestSupport.unique("cat")); String reader = tokenWith("CATEGORY:READ"); given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); @@ -198,7 +198,7 @@ void readOnlyUserCanReadButNotWrite() { } @Test - void userWithoutPermissionIs403AndNoTokenIs401() { + void _10_ShouldReturn403Or401_WhenUserLacksPermissionOrTokenMissing() { String nobody = support.token(support.createUser()); given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java index 3df8469..9e37a4f 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java @@ -69,7 +69,7 @@ private String tokenWith(String... permissions) { } @Test - void createReturns201WithEnvelope() { + void _01_ShouldReturn201WithEnvelope_WhenCreatingCustomer() { Long id = given().auth().oauth2(admin).contentType("application/json").body(VALID).when().post(BASE) .then().statusCode(201).contentType("application/json") .body("success", is(true)) @@ -84,7 +84,7 @@ void createReturns201WithEnvelope() { } @Test - void optionalFieldsMayBeOmittedOrNull() { + void _02_ShouldAcceptRequest_WhenOptionalFieldsOmittedOrNull() { Long id = createViaApi("{\"firstName\":\"Min\",\"lastName\":\"Imal\"}"); given().auth().oauth2(admin).when().get(BASE + "/" + id) .then().statusCode(200) @@ -99,7 +99,7 @@ void optionalFieldsMayBeOmittedOrNull() { } @Test - void getByIdAndUpdate() { + void _03_ShouldReturnAndUpdateCustomer_WhenCustomerExists() { Long id = createViaApi(VALID); given().auth().oauth2(admin).when().get(BASE + "/" + id) .then().statusCode(200).body("success", is(true)).body("data.id", is(id.intValue())); @@ -112,7 +112,7 @@ void getByIdAndUpdate() { } @Test - void listIsPaginatedAndOrderedById() { + void _04_ShouldPaginateAndOrderById_WhenListingCustomers() { Long a = createViaApi(VALID); Long b = createViaApi(VALID); Long c = createViaApi(VALID); @@ -131,7 +131,7 @@ void listIsPaginatedAndOrderedById() { } @Test - void invalidPageSizeIs400Problem() { + void _05_ShouldReturn400Problem_WhenPageSizeIsInvalid() { given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); given().auth().oauth2(admin).queryParam("size", 101).when().get(BASE) @@ -141,7 +141,7 @@ void invalidPageSizeIs400Problem() { } @Test - void unknownIdIs404Problem() { + void _06_ShouldReturn404Problem_WhenCustomerIdUnknown() { given().auth().oauth2(admin).when().get(BASE + "/999999999") .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) .body("$", not(hasKey("success"))); @@ -153,7 +153,7 @@ void unknownIdIs404Problem() { } @Test - void invalidBodyIs400ProblemWithViolations() { + void _07_ShouldReturn400ProblemWithViolations_WhenBodyInvalid() { List bodies = List.of( "{\"firstName\":\" \",\"lastName\":\"L\"}", "{\"firstName\":\"F\",\"lastName\":\"\"}", @@ -179,7 +179,7 @@ void invalidBodyIs400ProblemWithViolations() { } @Test - void deleteRemovesCustomer() { + void _08_ShouldRemoveCustomer_WhenDeleteSucceeds() { Long id = createViaApi(VALID); given().auth().oauth2(admin).when().delete(BASE + "/" + id) .then().statusCode(200).body("success", is(true)); @@ -187,7 +187,7 @@ void deleteRemovesCustomer() { } @Test - void readOnlyUserCanReadButNotWrite() { + void _09_ShouldAllowReadButNotWrite_WhenCallerIsReadOnly() { Long id = createViaApi(VALID); String reader = tokenWith("CUSTOMER:READ"); given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); @@ -202,7 +202,7 @@ void readOnlyUserCanReadButNotWrite() { } @Test - void writeOnlyUserCannotRead() { + void _10_ShouldReturn403_WhenWriteOnlyUserReads() { String writer = tokenWith("CUSTOMER:WRITE"); given().auth().oauth2(writer).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); Long id = given().auth().oauth2(writer).contentType("application/json").body(VALID).when().post(BASE) @@ -211,7 +211,7 @@ void writeOnlyUserCannotRead() { } @Test - void userWithoutPermissionIs403AndNoTokenIs401() { + void _11_ShouldReturn403Or401_WhenUserLacksPermissionOrTokenMissing() { String nobody = support.token(support.createUser()); given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java index 8773f39..ae897e2 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java @@ -30,7 +30,7 @@ class ForgotPasswordEnumerationTest { PasswordResetTokenRepository resetTokens; @Test - void registeredAndUnregisteredEmailsGetTheSameAnswer() { + void _01_ShouldGiveSameAnswer_WhenEmailIsRegisteredOrNot() { String known = "known" + System.nanoTime() + "@example.com"; given().contentType("application/json") .body("{\"firstName\":\"A\",\"lastName\":\"B\",\"email\":\"" + known + "\",\"password\":\"Str0ngPassw0rd!\"}") diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java index 5d8bb1c..b8ea733 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java @@ -67,7 +67,7 @@ void tearDown() { } @Test - void removingTheRoleFromTheLastHolderIsRejectedAndAudited() { + void _01_ShouldRejectAndAudit_WhenRemovingRoleFromLastHolder() { given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) .then().statusCode(422).contentType(PROBLEM_JSON) .body("status", is(422)).body("detail", containsString("ROLE:WRITE")) @@ -83,7 +83,7 @@ void removingTheRoleFromTheLastHolderIsRejectedAndAudited() { } @Test - void removingRoleWritePermissionFromTheOnlySourceIsRejectedAndAudited() { + void _02_ShouldRejectAndAudit_WhenRemovingRoleWriteFromOnlySource() { given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId + "/permissions/" + roleWritePermissionId) .then().statusCode(422).contentType(PROBLEM_JSON) .body("status", is(422)).body("detail", containsString("ROLE:WRITE")) @@ -97,7 +97,7 @@ void removingRoleWritePermissionFromTheOnlySourceIsRejectedAndAudited() { } @Test - void roleRemovalIsAllowedWhenAnotherUserStillHoldsRoleWrite() { + void _03_ShouldAllowRoleRemoval_WhenAnotherUserStillHoldsRoleWrite() { TestUser second = support.createUser(); support.grantRole(second.id(), roleId); given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) @@ -105,7 +105,7 @@ void roleRemovalIsAllowedWhenAnotherUserStillHoldsRoleWrite() { } @Test - void roleRemovalIsAllowedWhenTheUserKeepsRoleWriteThroughAnotherRole() { + void _04_ShouldAllowRoleRemoval_WhenUserKeepsRoleWriteThroughAnotherRole() { Long backup = support.createRole(RbacTestSupport.unique("backup"), "ROLE:WRITE"); support.grantRole(admin.id(), backup); given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) @@ -113,7 +113,7 @@ void roleRemovalIsAllowedWhenTheUserKeepsRoleWriteThroughAnotherRole() { } @Test - void permissionRemovalIsAllowedWhenAnotherRoleStillGrantsItToAHolder() { + void _05_ShouldAllowPermissionRemoval_WhenAnotherRoleStillGrantsItToAHolder() { Long backup = support.createRole(RbacTestSupport.unique("backup"), "ROLE:WRITE"); TestUser second = support.createUser(); support.grantRole(second.id(), backup); @@ -123,7 +123,7 @@ void permissionRemovalIsAllowedWhenAnotherRoleStillGrantsItToAHolder() { @ParameterizedTest @CsvSource({"false,false", "true,true"}) - void inactiveOtherHolderDoesNotCountAsAnotherAdmin(boolean enabled, boolean locked) { + void _06_ShouldNotCountAsAnotherAdmin_WhenOtherHolderIsDisabledOrLocked(boolean enabled, boolean locked) { // The other holder is disabled (or locked): they cannot act, so the caller is the last active admin. TestUser other = support.createUser(); support.grantRole(other.id(), roleId); @@ -136,7 +136,7 @@ void inactiveOtherHolderDoesNotCountAsAnotherAdmin(boolean enabled, boolean lock } @Test - void enabledUnlockedOtherHolderAllowsRemoval() { + void _07_ShouldAllowRemoval_WhenOtherHolderIsEnabledAndUnlocked() { TestUser other = support.createUser(); support.grantRole(other.id(), roleId); support.setStatus(other.id(), true, false); @@ -145,7 +145,7 @@ void enabledUnlockedOtherHolderAllowsRemoval() { } @Test - void concurrentCrossRemovalsNeverLeaveZeroActiveAdmins() throws Exception { + void _08_ShouldNeverLeaveZeroActiveAdmins_WhenRemovalsRunConcurrently() throws Exception { // Admin A holds roleId, admin B holds roleB; each removes the other's role at the same instant. // The advisory lock in removeRoleFromUser serialises them, so the second one sees the first commit. Long roleB = support.createRole(RbacTestSupport.unique("last-admin-b"), "ROLE:WRITE", "ROLE:READ", diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java index b026414..32e1ee5 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java @@ -112,7 +112,7 @@ private String tokenWith(String... permissions) { } @Test - void createReturns201WithComputedTotalAndDetailRoundTrips() { + void _01_ShouldReturn201WithComputedTotal_WhenCreatingOrder() { Long cust = customer(); Long prod = product(category(), "2.50"); @@ -138,7 +138,7 @@ void createReturns201WithComputedTotalAndDetailRoundTrips() { } @Test - void totalIsFrozenWhenTheProductPriceChangesLater() { + void _02_ShouldKeepTotalFrozen_WhenProductPriceChangesLater() { Long cat = category(); Long cust = customer(); Long prod = product(cat, "4.00"); @@ -157,14 +157,14 @@ void totalIsFrozenWhenTheProductPriceChangesLater() { } @Test - void unknownOrderIs404Problem() { + void _03_ShouldReturn404Problem_WhenOrderIdUnknown() { given().auth().oauth2(admin).when().get(BASE + "/999999999") .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) .body("$", not(hasKey("success"))); } @Test - void listIsPaginatedAndFilteredByCustomerProductOrBoth() { + void _04_ShouldPaginateAndFilter_WhenListingByCustomerProductOrBoth() { Long cat = category(); Long custA = customer(); Long custB = customer(); @@ -205,13 +205,13 @@ void listIsPaginatedAndFilteredByCustomerProductOrBoth() { } @Test - void invalidPageSizeIs400Problem() { + void _05_ShouldReturn400Problem_WhenPageSizeIsInvalid() { given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); } @Test - void invalidBodyIs400ProblemWithViolations() { + void _06_ShouldReturn400ProblemWithViolations_WhenBodyInvalid() { Long cust = customer(); Long prod = product(category(), "1.00"); List bodies = List.of( @@ -231,7 +231,7 @@ void invalidBodyIs400ProblemWithViolations() { } @Test - void unknownCustomerOrProductIs422Problem() { + void _07_ShouldReturn422Problem_WhenCustomerOrProductUnknown() { Long cust = customer(); Long prod = product(category(), "1.00"); given().auth().oauth2(admin).contentType(JSON).body(body(999999999, prod, 1)).when().post(BASE) @@ -242,7 +242,7 @@ void unknownCustomerOrProductIs422Problem() { } @Test - void totalBeyondNumeric14Is422ProblemAndLargestFittingTotalIsAccepted() { + void _08_ShouldReturn422Problem_WhenTotalExceedsNumeric14() { Long cust = customer(); Long prod = product(category(), "9999999999.99"); given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 100)).when().post(BASE) @@ -256,7 +256,7 @@ void totalBeyondNumeric14Is422ProblemAndLargestFittingTotalIsAccepted() { } @Test - void readerCanReadButNotCreateAndWriterCanCreate() { + void _09_ShouldAllowReadButNotCreate_WhenCallerIsReader() { Long cust = customer(); Long prod = product(category(), "1.00"); Long id = order(cust, prod, 1); @@ -273,7 +273,7 @@ void readerCanReadButNotCreateAndWriterCanCreate() { } @Test - void userWithoutPermissionIs403AndNoTokenIs401() { + void _10_ShouldReturn403Or401_WhenUserLacksPermissionOrTokenMissing() { String nobody = support.token(support.createUser()); given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); @@ -284,7 +284,7 @@ void userWithoutPermissionIs403AndNoTokenIs401() { } @Test - void productWithOrdersCannotBeDeletedUntilOrdersAreGone() { + void _11_ShouldRefuseProductDeletion_WhenProductHasOrders() { Long cust = customer(); Long prod = product(category(), "1.00"); order(cust, prod, 1); @@ -298,7 +298,7 @@ void productWithOrdersCannotBeDeletedUntilOrdersAreGone() { } @Test - void customerWithOrdersCannotBeDeletedUntilOrdersAreGone() { + void _12_ShouldRefuseCustomerDeletion_WhenCustomerHasOrders() { Long cust = customer(); Long prod = product(category(), "1.00"); order(cust, prod, 1); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java index 4e316ef..b1f2515 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java @@ -97,19 +97,19 @@ private HttpRequest.Builder streamRequest(String token) { } @Test - void streamWithoutTokenIs401() { + void _01_ShouldReturn401_WhenStreamOpenedWithoutToken() { given().accept("text/event-stream").when().get(STREAM).then().statusCode(401); } @Test - void streamWithoutOrderReadIs403Problem() { + void _02_ShouldReturn403Problem_WhenStreamOpenedWithoutOrderRead() { String token = tokenWith("ORDER:WRITE"); given().auth().oauth2(token).accept("text/event-stream").when().get(STREAM) .then().statusCode(403).contentType(PROBLEM_JSON); } @Test - void createdOrderIsPushedAsADataEventWithEventStreamContentType() throws Exception { + void _03_ShouldPushDataEventWithEventStreamContentType_WhenOrderCreated() throws Exception { Long category = given().auth().oauth2(admin).contentType(JSON) .body("{\"categoryName\":\"" + RbacTestSupport.unique("cat") + "\"}").when() .post("/api/v1/categories").then().statusCode(201).extract().jsonPath().getLong("data.id"); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java index 0a5003d..86fd653 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java @@ -48,7 +48,7 @@ private Long createViaApi(String resource, String action) { } @Test - void listReturnsSeededCatalog() { + void _01_ShouldReturnSeededCatalog_WhenListingPermissions() { given().auth().oauth2(admin).when().get(BASE) .then().statusCode(200).contentType("application/json") .body("success", is(true)) @@ -57,7 +57,7 @@ void listReturnsSeededCatalog() { } @Test - void createNormalisesToUpperCase() { + void _02_ShouldNormaliseToUpperCase_WhenCreatingPermission() { String resource = RbacTestSupport.unique("res").toUpperCase(); given().auth().oauth2(admin).contentType("application/json") .body("{\"resource\":\"" + resource.toLowerCase() + "\",\"action\":\"exec\"}") @@ -68,7 +68,7 @@ void createNormalisesToUpperCase() { } @Test - void duplicatePairIs422Problem() { + void _03_ShouldReturn422Problem_WhenPermissionPairIsDuplicated() { String resource = RbacTestSupport.unique("res").toUpperCase(); createViaApi(resource, "READ"); given().auth().oauth2(admin).contentType("application/json") @@ -80,14 +80,14 @@ void duplicatePairIs422Problem() { } @Test - void blankFieldsAre400ValidationProblem() { + void _04_ShouldReturn400ValidationProblem_WhenFieldsAreBlank() { given().auth().oauth2(admin).contentType("application/json").body("{\"resource\":\"\",\"action\":\"\"}") .when().post(BASE) .then().statusCode(400).contentType(PROBLEM_JSON).body("status", is(400)); } @Test - void updateChangesPairAndRejectsDuplicateOrUnknown() { + void _05_ShouldChangePairAndRejectDuplicateOrUnknown_WhenUpdatingPermission() { String resource = RbacTestSupport.unique("res").toUpperCase(); Long id = createViaApi(resource, "READ"); createViaApi(resource, "WRITE"); @@ -105,7 +105,7 @@ void updateChangesPairAndRejectsDuplicateOrUnknown() { } @Test - void deleteRemovesPermissionThenIs404() { + void _06_ShouldReturn404AfterRemoval_WhenPermissionDeleted() { Long id = createViaApi(RbacTestSupport.unique("res").toUpperCase(), "READ"); given().auth().oauth2(admin).when().delete(BASE + "/" + id) .then().statusCode(200).body("success", is(true)); @@ -114,7 +114,7 @@ void deleteRemovesPermissionThenIs404() { } @Test - void readerCanListButNotWrite() { + void _07_ShouldAllowListButNotWrite_WhenCallerIsReader() { support.createRole("perm-reader", "PERMISSION:READ"); String token = support.token(support.createUser("perm-reader")); given().auth().oauth2(token).when().get(BASE).then().statusCode(200); @@ -126,7 +126,7 @@ void readerCanListButNotWrite() { } @Test - void userWithoutRolesIsForbiddenAndAnonymousIs401() { + void _08_ShouldReturn403Or401_WhenUserHasNoRolesOrIsAnonymous() { String token = support.token(support.createUser()); given().auth().oauth2(token).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); given().when().get(BASE).then().statusCode(401).contentType(PROBLEM_JSON).body("status", is(401)); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java index 8203e69..8a61f76 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java @@ -89,7 +89,7 @@ private String tokenWith(String... permissions) { } @Test - void createReturns201WithEnvelopeAndMoneyRoundTrips() { + void _01_ShouldReturn201WithEnvelopeAndKeepMoney_WhenCreatingProduct() { Long cat = category(); String json = given().auth().oauth2(admin).contentType("application/json") .body(body(cat, "Keyboard", "79.99")).when().post(BASE) @@ -110,7 +110,7 @@ void createReturns201WithEnvelopeAndMoneyRoundTrips() { } @Test - void getByIdAndUpdate() { + void _02_ShouldReturnAndUpdateProduct_WhenProductExists() { Long cat = category(); Long other = category(); Long id = product(cat, "Mouse", "10.50"); @@ -129,7 +129,7 @@ void getByIdAndUpdate() { } @Test - void listIsPaginatedAndOrderedById() { + void _03_ShouldPaginateAndOrderById_WhenListingProducts() { Long cat = category(); Long a = product(cat, "A", "1.00"); Long b = product(cat, "B", "2.00"); @@ -151,7 +151,7 @@ void listIsPaginatedAndOrderedById() { } @Test - void categoryFilterReturnsOnlyRequestedCategory() { + void _04_ShouldReturnOnlyRequestedCategory_WhenCategoryFilterGiven() { Long catA = category(); Long catB = category(); Long a1 = product(catA, "A1", "1.00"); @@ -177,13 +177,13 @@ void categoryFilterReturnsOnlyRequestedCategory() { } @Test - void invalidPageSizeIs400Problem() { + void _05_ShouldReturn400Problem_WhenPageSizeIsInvalid() { given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); } @Test - void unknownIdIs404Problem() { + void _06_ShouldReturn404Problem_WhenProductIdUnknown() { Long cat = category(); given().auth().oauth2(admin).when().get(BASE + "/999999999") .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) @@ -196,7 +196,7 @@ void unknownIdIs404Problem() { } @Test - void invalidBodyIs400ProblemWithViolations() { + void _07_ShouldReturn400ProblemWithViolations_WhenBodyInvalid() { Long cat = category(); List bodies = List.of( body(cat, " ", "1.00"), @@ -219,7 +219,7 @@ void invalidBodyIs400ProblemWithViolations() { } @Test - void unknownCategoryIs422ProblemOnCreateAndUpdate() { + void _08_ShouldReturn422Problem_WhenCategoryUnknownOnCreateOrUpdate() { Long cat = category(); given().auth().oauth2(admin).contentType("application/json").body(body(999999999, "Ghost", "1.00")) .when().post(BASE) @@ -235,7 +235,7 @@ void unknownCategoryIs422ProblemOnCreateAndUpdate() { } @Test - void deleteRemovesProduct() { + void _09_ShouldRemoveProduct_WhenDeleteSucceeds() { Long id = product(category(), "Gone", "1.00"); given().auth().oauth2(admin).when().delete(BASE + "/" + id) .then().statusCode(200).body("success", is(true)); @@ -243,7 +243,7 @@ void deleteRemovesProduct() { } @Test - void categoryWithProductsCannotBeDeletedUntilProductIsDeleted() { + void _10_ShouldAllowCategoryDeletion_WhenItsProductIsDeleted() { Long cat = category(); Long id = product(cat, "Blocker", "1.00"); given().auth().oauth2(admin).when().delete(CATEGORIES + "/" + cat) @@ -254,7 +254,7 @@ void categoryWithProductsCannotBeDeletedUntilProductIsDeleted() { } @Test - void readOnlyUserCanReadButNotWrite() { + void _11_ShouldAllowReadButNotWrite_WhenCallerIsReadOnly() { Long cat = category(); Long id = product(cat, "Shared", "1.00"); String reader = tokenWith("PRODUCT:READ"); @@ -271,7 +271,7 @@ void readOnlyUserCanReadButNotWrite() { } @Test - void userWithoutPermissionIs403AndNoTokenIs401() { + void _12_ShouldReturn403Or401_WhenUserLacksPermissionOrTokenMissing() { String nobody = support.token(support.createUser()); given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java index 7a24d7e..78731b0 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java @@ -55,7 +55,7 @@ private Long post(String url, String body) { } @Test - void roleCreateUpdateDeleteAreAudited() { + void _01_ShouldAudit_WhenRoleCreatedUpdatedOrDeleted() { Long id = post("/api/v1/roles", "{\"roleName\":\"" + RbacTestSupport.unique("audit") + "\"}"); support.trackRole(id); assertAudited("ROLE_CREATED", "ROLE", id); @@ -70,7 +70,7 @@ void roleCreateUpdateDeleteAreAudited() { } @Test - void permissionCreateUpdateDeleteAreAudited() { + void _02_ShouldAudit_WhenPermissionCreatedUpdatedOrDeleted() { String resource = RbacTestSupport.unique("res").toUpperCase(); Long id = post("/api/v1/permissions", "{\"resource\":\"" + resource + "\",\"action\":\"READ\"}"); support.trackPermission(id); @@ -86,7 +86,7 @@ void permissionCreateUpdateDeleteAreAudited() { } @Test - void permissionAssignAndRemoveOnARoleAreAudited() { + void _03_ShouldAudit_WhenPermissionAssignedOrRemovedOnRole() { Long roleId = support.createRole(RbacTestSupport.unique("audit")); Long permissionId = support.permissionId("CATEGORY", "READ"); given().auth().oauth2(token).when().post("/api/v1/roles/" + roleId + "/permissions/" + permissionId) @@ -102,7 +102,7 @@ void permissionAssignAndRemoveOnARoleAreAudited() { } @Test - void roleAssignAndRemoveOnAUserAreAudited() { + void _04_ShouldAudit_WhenRoleAssignedOrRemovedOnUser() { Long roleId = support.createRole(RbacTestSupport.unique("audit")); TestUser target = support.createUser(); given().auth().oauth2(token).when().patch("/api/v1/users/" + target.id() + "/roles/" + roleId) @@ -115,7 +115,7 @@ void roleAssignAndRemoveOnAUserAreAudited() { } @Test - void rejectedDeletesAreAuditedDespiteTheRollback() { + void _05_ShouldAuditRejection_WhenDeleteIsRolledBack() { Long roleId = support.createRole(RbacTestSupport.unique("audit")); TestUser holder = support.createUser(); support.grantRole(holder.id(), roleId); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java index e1e5ff0..2aaa7c3 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java @@ -40,7 +40,7 @@ void tearDown() { } @Test - void roleAssignedToAUserCannotBeDeletedUntilUnassigned() { + void _01_ShouldRejectRoleDeletion_WhenRoleIsAssignedToUser() { Long roleId = support.createRole(RbacTestSupport.unique("held")); TestUser holder = support.createUser(); support.grantRole(holder.id(), roleId); @@ -61,7 +61,7 @@ void roleAssignedToAUserCannotBeDeletedUntilUnassigned() { } @Test - void permissionAssignedToARoleCannotBeDeletedUntilUnassigned() { + void _02_ShouldRejectPermissionDeletion_WhenPermissionIsAssignedToRole() { Long permissionId = support.createPermission(RbacTestSupport.unique("res").toUpperCase(), "READ"); Long roleId = support.createRole(RbacTestSupport.unique("carrier")); given().auth().oauth2(admin).when().post("/api/v1/roles/" + roleId + "/permissions/" + permissionId) diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java index 5a636ae..826782b 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java @@ -50,7 +50,7 @@ private Long createRoleViaApi(String name) { } @Test - void listIncludesSeededAdminWithItsPermissions() { + void _01_ShouldIncludeSeededAdminWithPermissions_WhenListingRoles() { given().auth().oauth2(admin).when().get(BASE) .then().statusCode(200).contentType("application/json") .body("success", is(true)) @@ -59,7 +59,7 @@ void listIncludesSeededAdminWithItsPermissions() { } @Test - void createReturns201WithEnvelope() { + void _02_ShouldReturn201WithEnvelope_WhenCreatingRole() { String name = RbacTestSupport.unique("role"); given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + name + "\"}") .when().post(BASE) @@ -72,7 +72,7 @@ void createReturns201WithEnvelope() { } @Test - void duplicateNameIs422Problem() { + void _03_ShouldReturn422Problem_WhenRoleNameIsDuplicated() { String name = RbacTestSupport.unique("role"); createRoleViaApi(name); given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + name + "\"}") @@ -85,7 +85,7 @@ void duplicateNameIs422Problem() { } @Test - void blankNameIs400ValidationProblem() { + void _04_ShouldReturn400ValidationProblem_WhenRoleNameIsBlank() { given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\" \"}") .when().post(BASE) .then().statusCode(400).contentType(PROBLEM_JSON) @@ -94,7 +94,7 @@ void blankNameIs400ValidationProblem() { } @Test - void updateRenamesRoleAndRejectsDuplicateOrUnknown() { + void _05_ShouldRenameRoleAndRejectDuplicateOrUnknown_WhenUpdatingRole() { Long id = createRoleViaApi(RbacTestSupport.unique("role")); Long other = createRoleViaApi(RbacTestSupport.unique("role")); String renamed = RbacTestSupport.unique("renamed"); @@ -113,7 +113,7 @@ void updateRenamesRoleAndRejectsDuplicateOrUnknown() { } @Test - void deleteRemovesRoleThenIs404() { + void _06_ShouldReturn404AfterRemoval_WhenRoleDeleted() { Long id = createRoleViaApi(RbacTestSupport.unique("role")); given().auth().oauth2(admin).when().delete(BASE + "/" + id) .then().statusCode(200).body("success", is(true)).body("message", is("Role deleted")); @@ -122,7 +122,7 @@ void deleteRemovesRoleThenIs404() { } @Test - void assignAndRemovePermission() { + void _07_ShouldAssignAndRemovePermission_WhenManagingRolePermissions() { Long id = createRoleViaApi(RbacTestSupport.unique("role")); Long readCategory = support.permissionId("CATEGORY", "READ"); given().auth().oauth2(admin).when().post(BASE + "/" + id + "/permissions/" + readCategory) @@ -138,7 +138,7 @@ void assignAndRemovePermission() { } @Test - void assignUnknownPermissionOrRoleIs404() { + void _08_ShouldReturn404_WhenAssigningUnknownPermissionOrRole() { Long id = createRoleViaApi(RbacTestSupport.unique("role")); given().auth().oauth2(admin).when().post(BASE + "/" + id + "/permissions/999999999") .then().statusCode(404).contentType(PROBLEM_JSON); @@ -147,7 +147,7 @@ void assignUnknownPermissionOrRoleIs404() { } @Test - void readerCanListButNotWrite() { + void _09_ShouldAllowListButNotWrite_WhenCallerIsReader() { support.createRole("reader-role", "ROLE:READ"); TestUser reader = support.createUser("reader-role"); String token = support.token(reader); @@ -160,14 +160,14 @@ void readerCanListButNotWrite() { } @Test - void userWithoutAnyRoleIsForbidden() { + void _10_ShouldReturn403_WhenUserHasNoRole() { String token = support.token(support.createUser()); given().auth().oauth2(token).when().get(BASE) .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); } @Test - void missingTokenIs401Problem() { + void _11_ShouldReturn401Problem_WhenTokenMissing() { given().when().get(BASE) .then().statusCode(401).contentType(PROBLEM_JSON).body("status", is(401)) .body("$", not(hasKey("success"))); diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java index c9e6b84..828c256 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java @@ -41,7 +41,7 @@ void tearDown() { } @Test - void listIsPaginatedInsideTheEnvelope() { + void _01_ShouldPaginateInsideEnvelope_WhenListingUsers() { support.createUser(); support.createUser(); given().auth().oauth2(admin).queryParam("page", 0).queryParam("size", 2).when().get(BASE) @@ -56,7 +56,7 @@ void listIsPaginatedInsideTheEnvelope() { } @Test - void invalidPagingIs400Problem() { + void _02_ShouldReturn400Problem_WhenPagingIsInvalid() { given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) .then().statusCode(400).contentType(PROBLEM_JSON).body("status", is(400)) .body("$", not(hasKey("success"))); @@ -67,7 +67,7 @@ void invalidPagingIs400Problem() { } @Test - void detailIncludesAssignedRoles() { + void _03_ShouldIncludeAssignedRoles_WhenReadingUserDetail() { TestUser target = support.createUser("ADMIN"); given().auth().oauth2(admin).when().get(BASE + "/" + target.id()) .then().statusCode(200) @@ -78,13 +78,13 @@ void detailIncludesAssignedRoles() { } @Test - void unknownUserIs404Problem() { + void _04_ShouldReturn404Problem_WhenUserUnknown() { given().auth().oauth2(admin).when().get(BASE + "/999999999") .then().statusCode(404).contentType(PROBLEM_JSON).body("title", is("Resource Not Found")); } @Test - void assignThenRemoveRole() { + void _05_ShouldAssignThenRemoveRole_WhenManagingUserRoles() { Long roleId = support.createRole(RbacTestSupport.unique("plain")); TestUser target = support.createUser(); given().auth().oauth2(admin).when().patch(BASE + "/" + target.id() + "/roles/" + roleId) @@ -99,7 +99,7 @@ void assignThenRemoveRole() { } @Test - void assignWithUnknownUserOrRoleIs404() { + void _06_ShouldReturn404_WhenAssigningWithUnknownUserOrRole() { TestUser target = support.createUser(); given().auth().oauth2(admin).when().patch(BASE + "/999999999/roles/" + support.roleId("ADMIN")) .then().statusCode(404).contentType(PROBLEM_JSON); @@ -108,7 +108,7 @@ void assignWithUnknownUserOrRoleIs404() { } @Test - void thereIsNoUserCreationEndpoint() { + void _07_ShouldNotExposeCreationEndpoint_WhenPostingUser() { // Users are created by feature/auth's register endpoint only, never by UserResource. given().auth().oauth2(admin).contentType("application/json").body("{\"email\":\"a@b.c\"}") .when().post(BASE).then().statusCode(405); @@ -117,7 +117,7 @@ void thereIsNoUserCreationEndpoint() { } @Test - void readerCanReadButNotAssign() { + void _08_ShouldAllowReadButNotAssign_WhenCallerIsReader() { support.createRole("user-reader", "USER:READ"); TestUser reader = support.createUser("user-reader"); String token = support.token(reader); @@ -130,7 +130,7 @@ void readerCanReadButNotAssign() { } @Test - void userWithoutRolesIsForbiddenAndAnonymousIs401() { + void _09_ShouldReturn403Or401_WhenUserHasNoRolesOrIsAnonymous() { String token = support.token(support.createUser()); given().auth().oauth2(token).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); given().when().get(BASE).then().statusCode(401).contentType(PROBLEM_JSON).body("status", is(401)); diff --git a/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java b/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java index f93173f..944e9d2 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java @@ -90,7 +90,7 @@ private long count(String tag) { } @Test - void deletesExpiredRowsOfAllThreeTablesAndKeepsTheRest() { + void _01_ShouldDeleteExpiredRowsOfAllTables_WhenJobRuns() { // Purge anything expired that other test classes left, so the count below is exact. job.cleanup(); TestUser owner = support.createUser(); diff --git a/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java b/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java index 65fe5e5..3efab56 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java @@ -29,7 +29,7 @@ class AuditLoggerTransactionTest { RbacTestSupport support; @Test - void successRowIsRolledBackWithTheBusinessTransaction() { + void _01_ShouldRollBackSuccessRow_WhenBusinessTransactionRollsBack() { String action = RbacTestSupport.unique("TX_SUCCESS"); assertThrows(IllegalStateException.class, () -> QuarkusTransaction.requiringNew().run(() -> { auditLogger.log(action, "TEST", 1L, "must vanish"); @@ -39,14 +39,14 @@ void successRowIsRolledBackWithTheBusinessTransaction() { } @Test - void successRowIsKeptWhenTheTransactionCommits() { + void _02_ShouldKeepSuccessRow_WhenTransactionCommits() { String action = RbacTestSupport.unique("TX_COMMIT"); QuarkusTransaction.requiringNew().run(() -> auditLogger.log(action, "TEST", 2L, "kept")); assertEquals(1, support.audit(action, "TEST", 2L).size()); } @Test - void rejectedRowSurvivesTheCallersRollback() { + void _03_ShouldKeepRejectedRow_WhenCallerRollsBack() { String action = RbacTestSupport.unique("TX_REJECTED"); assertThrows(IllegalStateException.class, () -> QuarkusTransaction.requiringNew().run(() -> { auditLogger.logRejected(action, "TEST", 3L, "must survive"); diff --git a/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java b/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java index 751afb6..06da129 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java @@ -49,7 +49,7 @@ private static PublicKey devPublicKey() throws Exception { } @Test - void tokenVerifiesWithDevPublicKeyAndCarriesExpectedClaims() throws Exception { + void _01_ShouldVerifyWithPublicKeyAndCarryExpectedClaims_WhenTokenIssued() throws Exception { long before = System.currentTimeMillis() / 1000; AuthResponse response = issuer.issue(user(42L)); @@ -65,7 +65,7 @@ void tokenVerifiesWithDevPublicKeyAndCarriesExpectedClaims() throws Exception { } @Test - void eachIssuedTokenHasAUniqueJti() throws Exception { + void _02_ShouldGiveUniqueJti_WhenTokensIssuedTwice() throws Exception { PublicKey key = devPublicKey(); String first = parser.verify(issuer.issue(user(1L)).token(), key).getTokenID(); String second = parser.verify(issuer.issue(user(1L)).token(), key).getTokenID(); diff --git a/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java b/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java index 02314ba..0922767 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java @@ -63,7 +63,7 @@ private static boolean has(SecurityIdentity identity, String resource, String ac } @Test - void multiRoleUserGetsTheUnionOfPermissions() { + void _01_ShouldGrantUnionOfPermissions_WhenUserHasSeveralRoles() { support.createRole("aug-a", "USER:READ", "CATEGORY:READ"); support.createRole("aug-b", "CATEGORY:READ", "ORDER:WRITE"); TestUser user = support.createUser("aug-a", "aug-b"); @@ -76,7 +76,7 @@ void multiRoleUserGetsTheUnionOfPermissions() { } @Test - void userWithoutRolesGetsNoPermission() { + void _02_ShouldGrantNoPermission_WhenUserHasNoRole() { TestUser user = support.createUser(); SecurityIdentity identity = augmentFor(user.id()); assertFalse(has(identity, "USER", "READ")); @@ -84,13 +84,13 @@ void userWithoutRolesGetsNoPermission() { } @Test - void anonymousIdentityIsReturnedUnchanged() { + void _03_ShouldReturnIdentityUnchanged_WhenIdentityIsAnonymous() { SecurityIdentity anonymous = QuarkusSecurityIdentity.builder().setAnonymous(true).build(); assertSame(anonymous, augmentor.augment(anonymous, DIRECT).await().indefinitely()); } @Test - void permissionsAllowedEndpointFollowsTheAugmentedPermissions() { + void _04_ShouldFollowAugmentedPermissions_WhenCallingPermissionsAllowedEndpoint() { support.createRole("aug-c", "PERMISSION:READ"); String token = support.token(support.createUser("aug-c")); // PERMISSION:READ was resolved by the augmentor at request time: accepted here, rejected for USER:READ. diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java index 4d12a7e..92b3ff7 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java @@ -57,7 +57,7 @@ void setUp() { } @Test - void loginUnknownEmailFailsWithSameMessageAsWrongPassword() { + void _01_ShouldFailWithSameMessageAsWrongPassword_WhenEmailIsUnknown() { User user = new User(); user.setPassword(BcryptUtil.bcryptHash("Correct-horse-1")); user.setEnabled(true); @@ -75,7 +75,7 @@ void loginUnknownEmailFailsWithSameMessageAsWrongPassword() { } @Test - void registerDuplicateThrowsBusinessRule() { + void _02_ShouldThrowBusinessRule_WhenRegisteringDuplicate() { when(users.findByEmail("dup@example.com")).thenReturn(Optional.of(new User())); assertThrows(BusinessRuleException.class, () -> service.register(new RegisterRequest("A", "B", "dup@example.com", "Str0ngPassw0rd!"))); @@ -83,7 +83,7 @@ void registerDuplicateThrowsBusinessRule() { } @Test - void activateAccountWithExpiredTokenIsRejected() { + void _03_ShouldRejectActivation_WhenTokenExpired() { ActivationToken token = new ActivationToken(); User user = new User(); token.setUser(user); @@ -96,7 +96,7 @@ void activateAccountWithExpiredTokenIsRejected() { } @Test - void logoutIsIdempotent() { + void _04_ShouldStaySuccessful_WhenLogoutCalledTwice() { when(blacklist.existsByJti("jti-1")).thenReturn(false, true); when(users.findById(7L)).thenReturn(new User()); @@ -107,7 +107,7 @@ void logoutIsIdempotent() { } @Test - void resetPasswordWithExpiredTokenIsRejected() { + void _05_ShouldRejectReset_WhenTokenExpired() { PasswordResetToken token = new PasswordResetToken(); User user = new User(); user.setPassword("old-hash"); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java index 7d12dfc..572fa37 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java @@ -53,7 +53,7 @@ private static Category category(Long id, String name) { } @Test - void deleteIsRefusedWhenCategoryHasProducts() { + void _01_ShouldRefuseDeletion_WhenCategoryHasProducts() { Category c = category(1L, "Books"); when(repository.findById(1L)).thenReturn(c); when(productRepository.countByCategoryId(1L)).thenReturn(2L); @@ -63,7 +63,7 @@ void deleteIsRefusedWhenCategoryHasProducts() { } @Test - void deleteRemovesCategoryWithoutProducts() { + void _02_ShouldRemoveCategory_WhenCategoryHasNoProducts() { Category c = category(1L, "Books"); when(repository.findById(1L)).thenReturn(c); when(productRepository.countByCategoryId(1L)).thenReturn(0L); @@ -74,7 +74,7 @@ void deleteRemovesCategoryWithoutProducts() { } @Test - void deleteMissingCategoryIsNotFound() { + void _03_ShouldThrowNotFound_WhenDeletingMissingCategory() { when(repository.findById(9L)).thenReturn(null); assertThrows(ResourceNotFoundException.class, () -> service.delete(9L)); @@ -82,7 +82,7 @@ void deleteMissingCategoryIsNotFound() { } @Test - void updateMissingCategoryIsNotFound() { + void _04_ShouldThrowNotFound_WhenUpdatingMissingCategory() { when(repository.findById(9L)).thenReturn(null); assertThrows(ResourceNotFoundException.class, () -> service.update(9L, new CategoryRequest("x"))); @@ -90,7 +90,7 @@ void updateMissingCategoryIsNotFound() { @Test @SuppressWarnings("unchecked") - void listBuildsPageResponse() { + void _05_ShouldBuildPageResponse_WhenListingCategories() { PanacheQuery all = mock(PanacheQuery.class); PanacheQuery paged = mock(PanacheQuery.class); when(repository.findAll(any(Sort.class))).thenReturn(all); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java index efe59a5..beaa974 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java @@ -57,7 +57,7 @@ private static Customer customer(Long id, String first) { } @Test - void findByIdMapsEntity() { + void _01_ShouldMapEntity_WhenFindingById() { when(repository.findById(1L)).thenReturn(customer(1L, "Ada")); CustomerResponse r = service.findById(1L); @@ -66,14 +66,14 @@ void findByIdMapsEntity() { } @Test - void findByIdMissingIsNotFound() { + void _02_ShouldThrowNotFound_WhenFindingMissingCustomer() { when(repository.findById(9L)).thenReturn(null); assertThrows(ResourceNotFoundException.class, () -> service.findById(9L)); } @Test - void createPersistsMappedEntityIncludingNullOptionals() { + void _03_ShouldPersistMappedEntityWithNullOptionals_WhenCreatingCustomer() { CustomerResponse r = service.create(new CustomerRequest("Ada", "Lovelace", null, null, null)); ArgumentCaptor saved = ArgumentCaptor.forClass(Customer.class); @@ -88,7 +88,7 @@ void createPersistsMappedEntityIncludingNullOptionals() { } @Test - void updateOverwritesAllFields() { + void _04_ShouldOverwriteAllFields_WhenUpdatingCustomer() { Customer existing = customer(1L, "Old"); when(repository.findById(1L)).thenReturn(existing); @@ -103,7 +103,7 @@ void updateOverwritesAllFields() { } @Test - void updateMissingIsNotFound() { + void _05_ShouldThrowNotFound_WhenUpdatingMissingCustomer() { when(repository.findById(9L)).thenReturn(null); assertThrows(ResourceNotFoundException.class, @@ -111,7 +111,7 @@ void updateMissingIsNotFound() { } @Test - void deleteRemovesCustomer() { + void _06_ShouldRemoveCustomer_WhenCustomerExists() { Customer c = customer(1L, "Ada"); when(repository.findById(1L)).thenReturn(c); @@ -121,7 +121,7 @@ void deleteRemovesCustomer() { } @Test - void deleteIsRefusedWhileOrdersReferenceTheCustomer() { + void _07_ShouldRefuseDeletion_WhenOrdersReferenceTheCustomer() { Customer c = customer(1L, "Ada"); when(repository.findById(1L)).thenReturn(c); when(orderRepository.countByCustomerId(1L)).thenReturn(2L); @@ -131,7 +131,7 @@ void deleteIsRefusedWhileOrdersReferenceTheCustomer() { } @Test - void deleteMissingIsNotFound() { + void _08_ShouldThrowNotFound_WhenDeletingMissingCustomer() { when(repository.findById(9L)).thenReturn(null); assertThrows(ResourceNotFoundException.class, () -> service.delete(9L)); @@ -140,7 +140,7 @@ void deleteMissingIsNotFound() { @Test @SuppressWarnings("unchecked") - void listBuildsPageResponse() { + void _09_ShouldBuildPageResponse_WhenListingCustomers() { PanacheQuery all = mock(PanacheQuery.class); PanacheQuery paged = mock(PanacheQuery.class); when(repository.findAll(any(Sort.class))).thenReturn(all); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java index bf441cb..5b765ad 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java @@ -143,7 +143,7 @@ private void assertMatches(OrderResponse expected, OrderResponse received) { } @Test - void committedOrderIsEmittedToTheSubscriber() { + void _01_ShouldEmitToSubscriber_WhenOrderCommitted() { AssertSubscriber subscriber = subscribe(); OrderResponse created = create(); @@ -154,7 +154,7 @@ void committedOrderIsEmittedToTheSubscriber() { } @Test - void rolledBackCreationEmitsNothing() { + void _02_ShouldEmitNothing_WhenOrderCreationRolledBack() { AssertSubscriber subscriber = subscribe(); assertThrows(BusinessRuleException.class, @@ -166,7 +166,7 @@ void rolledBackCreationEmitsNothing() { } @Test - void everyCurrentSubscriberReceivesTheEvent() { + void _03_ShouldDeliverToEverySubscriber_WhenOrderCreated() { AssertSubscriber first = subscribe(); AssertSubscriber second = subscribe(); OrderResponse created = create(); @@ -180,7 +180,7 @@ void everyCurrentSubscriberReceivesTheEvent() { } @Test - void lateSubscriberDoesNotReceiveAnAlreadyCreatedOrder() { + void _04_ShouldNotReplayOrder_WhenSubscriberJoinsLate() { AssertSubscriber early = subscribe(); create(); early.awaitItems(1, TIMEOUT); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java index 4d3883b..3be3aa6 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java @@ -80,7 +80,7 @@ private static Order order(Long id, Customer c, Product p, int quantity, String } @Test - void createComputesTotalFromCurrentUnitPriceWithScale2() { + void _01_ShouldComputeTotalFromCurrentUnitPriceWithScale2_WhenCreatingOrder() { when(customerRepository.findById(1L)).thenReturn(customer(1L)); when(productRepository.findById(2L)).thenReturn(product(2L, "2.50")); @@ -98,7 +98,7 @@ void createComputesTotalFromCurrentUnitPriceWithScale2() { } @Test - void createWithUnknownCustomerIsRefused() { + void _02_ShouldRefuseCreation_WhenCustomerUnknown() { when(customerRepository.findById(1L)).thenReturn(null); assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 1))); @@ -106,7 +106,7 @@ void createWithUnknownCustomerIsRefused() { } @Test - void createWithUnknownProductIsRefused() { + void _03_ShouldRefuseCreation_WhenProductUnknown() { when(customerRepository.findById(1L)).thenReturn(customer(1L)); when(productRepository.findById(2L)).thenReturn(null); @@ -115,7 +115,7 @@ void createWithUnknownProductIsRefused() { } @Test - void createWithTotalBeyondNumeric14IsRefused() { + void _04_ShouldRefuseCreation_WhenTotalExceedsNumeric14() { when(customerRepository.findById(1L)).thenReturn(customer(1L)); when(productRepository.findById(2L)).thenReturn(product(2L, "9999999999.99")); @@ -124,7 +124,7 @@ void createWithTotalBeyondNumeric14IsRefused() { } @Test - void createAcceptsTheLargestTotalThatFits() { + void _05_ShouldAcceptCreation_WhenTotalIsLargestThatFits() { when(customerRepository.findById(1L)).thenReturn(customer(1L)); when(productRepository.findById(2L)).thenReturn(product(2L, "9999999999.99")); @@ -135,7 +135,7 @@ void createAcceptsTheLargestTotalThatFits() { } @Test - void findByIdMapsAndMissingIsNotFound() { + void _06_ShouldMapOrThrowNotFound_WhenFindingById() { when(orderRepository.findById(5L)).thenReturn(order(5L, customer(1L), product(2L, "1.00"), 2, "2.00")); when(orderRepository.findById(9L)).thenReturn(null); @@ -148,7 +148,7 @@ void findByIdMapsAndMissingIsNotFound() { @Test @SuppressWarnings("unchecked") - void listBuildsPageResponseFromFilteredQueryAndCount() { + void _07_ShouldBuildPageResponse_WhenListingWithFilters() { PanacheQuery query = mock(PanacheQuery.class); PanacheQuery paged = mock(PanacheQuery.class); when(orderRepository.search(1L, null)).thenReturn(query); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java index 5f5c88e..3c57ead 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java @@ -91,7 +91,7 @@ private ProductResponse create(String name, String price) { } @Test - void secondReadIsServedFromCache() { + void _01_ShouldServeFromCache_WhenProductReadTwice() { Long id = create("Cached", "5.00").id(); Mockito.clearInvocations(productRepository); @@ -103,7 +103,7 @@ void secondReadIsServedFromCache() { } @Test - void updateEvictsEntryAndNextReadReloadsFreshData() { + void _02_ShouldReloadFreshData_WhenProductUpdated() { Long id = create("Before", "5.00").id(); assertEquals("Before", service.findById(id).productName()); @@ -120,7 +120,7 @@ void updateEvictsEntryAndNextReadReloadsFreshData() { } @Test - void deleteEvictsEntryAndNextReadIsNotFound() { + void _03_ShouldThrowNotFoundOnNextRead_WhenProductDeleted() { Long id = create("Doomed", "5.00").id(); service.findById(id); @@ -130,7 +130,7 @@ void deleteEvictsEntryAndNextReadIsNotFound() { } @Test - void notFoundIsNotCached() { + void _04_ShouldNotCacheNotFound_WhenProductMissing() { assertThrows(ResourceNotFoundException.class, () -> service.findById(999999999L)); assertThrows(ResourceNotFoundException.class, () -> service.findById(999999999L)); @@ -138,7 +138,7 @@ void notFoundIsNotCached() { } @Test - void createThenReadWorksAndIsCached() { + void _05_ShouldCacheProduct_WhenCreatedThenRead() { Long id = create("Fresh", "7.25").id(); Mockito.clearInvocations(productRepository); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java index 2b04b3e..fe51c34 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java @@ -66,7 +66,7 @@ private static Product product(Long id, Category category, String name, String p } @Test - void createWithUnknownCategoryIsRefused() { + void _01_ShouldRefuseCreation_WhenCategoryUnknown() { when(categoryRepository.findById(7L)).thenReturn(null); assertThrows(BusinessRuleException.class, @@ -75,7 +75,7 @@ void createWithUnknownCategoryIsRefused() { } @Test - void createScalesThePriceLikeTheDatabaseColumn() { + void _02_ShouldScalePriceLikeDatabaseColumn_WhenCreatingProduct() { when(categoryRepository.findById(1L)).thenReturn(category(1L)); ProductResponse response = service.create(new ProductRequest(1L, "Pen", new BigDecimal("10.5"))); @@ -84,7 +84,7 @@ void createScalesThePriceLikeTheDatabaseColumn() { } @Test - void createPersistsAndMapsResponse() { + void _03_ShouldPersistAndMapResponse_WhenCreatingProduct() { when(categoryRepository.findById(1L)).thenReturn(category(1L)); ProductResponse response = service.create(new ProductRequest(1L, "Pen", new BigDecimal("2.50"))); @@ -96,7 +96,7 @@ void createPersistsAndMapsResponse() { } @Test - void updateWithUnknownCategoryIsRefused() { + void _04_ShouldRefuseUpdate_WhenCategoryUnknown() { Product existing = product(3L, category(1L), "Old", "1.00"); when(productRepository.findById(3L)).thenReturn(existing); when(categoryRepository.findById(7L)).thenReturn(null); @@ -107,7 +107,7 @@ void updateWithUnknownCategoryIsRefused() { } @Test - void updateChangesFields() { + void _05_ShouldChangeFields_WhenUpdatingProduct() { Product existing = product(3L, category(1L), "Old", "1.00"); when(productRepository.findById(3L)).thenReturn(existing); when(categoryRepository.findById(2L)).thenReturn(category(2L)); @@ -120,7 +120,7 @@ void updateChangesFields() { } @Test - void missingProductIsNotFoundOnFindUpdateDelete() { + void _06_ShouldThrowNotFound_WhenProductMissingOnFindUpdateOrDelete() { when(productRepository.findById(9L)).thenReturn(null); assertThrows(ResourceNotFoundException.class, () -> service.findById(9L)); @@ -131,7 +131,7 @@ void missingProductIsNotFoundOnFindUpdateDelete() { } @Test - void deleteRemovesProduct() { + void _07_ShouldRemoveProduct_WhenProductExists() { Product existing = product(3L, category(1L), "Old", "1.00"); when(productRepository.findById(3L)).thenReturn(existing); @@ -141,7 +141,7 @@ void deleteRemovesProduct() { } @Test - void deleteIsRefusedWhileOrdersReferenceTheProduct() { + void _08_ShouldRefuseDeletion_WhenOrdersReferenceTheProduct() { Product existing = product(3L, category(1L), "Old", "1.00"); when(productRepository.findById(3L)).thenReturn(existing); when(orderRepository.countByProductId(3L)).thenReturn(1L); @@ -152,7 +152,7 @@ void deleteIsRefusedWhileOrdersReferenceTheProduct() { @Test @SuppressWarnings("unchecked") - void listWithoutFilterUsesGlobalCount() { + void _09_ShouldUseGlobalCount_WhenListingWithoutFilter() { PanacheQuery query = mock(PanacheQuery.class); PanacheQuery paged = mock(PanacheQuery.class); when(productRepository.findByCategory(null)).thenReturn(query); @@ -174,7 +174,7 @@ void listWithoutFilterUsesGlobalCount() { @Test @SuppressWarnings("unchecked") - void listWithCategoryFilterUsesCategoryCount() { + void _10_ShouldUseCategoryCount_WhenListingWithCategoryFilter() { PanacheQuery query = mock(PanacheQuery.class); PanacheQuery paged = mock(PanacheQuery.class); when(productRepository.findByCategory(4L)).thenReturn(query);