- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Challenge: Secure and Test an Auction Application with Spring Framework 6
In this compact yet comprehensive Code Lab, we'll journey into the realms of application security and testing with the cutting-edge Spring Framework 6. Our hands-on project will revolve around an auction application, which we'll secure and test. You'll gain practical proficiency in integrating Spring Security for managing authentication and authorization, You'll gain tangible experience in testing Spring 6 applications using tools like JUnit and Hamcrest, equipping you to write and execute a range of tests from unit and integration to end-to-end to ensure optimal functionality.In this compact yet comprehensive Code Lab, we'll journey into the realms of application security and testing with the cutting-edge Spring Framework 6. Our hands-on project will revolve around an auction application, which we'll secure and test. You'll gain practical proficiency in integrating Spring Security for managing authentication and authorization, You'll gain tangible experience in testing Spring 6 applications using tools like JUnit and Hamcrest, equipping you to write and execute a range of tests from unit and integration to end-to-end to ensure optimal functionality.
Lab Info
Table of Contents
-
Challenge
Item Class Testing
In this module you'll create a JUnit test for the
Itemclass.File: src/test/java/com/pluralsight/auction/ItemTest.java
Task 1: Define Test Variables In the
testItemmethod, define these variables:itemName: Set to "testItem".itemDescription: Set to "testDescription".itemSeller: Set to "testSeller".itemPrice: Set to 100.0.itemReserve: Set to 50.0.
Task 2: Instantiate the Item Using the variables from Task 1, instantiate an
Itemin thetestItemmethod.Task 3: Assert the Item's Properties In the
testItemmethod, validate theItem's properties usingassertEqualsstatements. Confirm that:- The item's name matches
itemName. - The item's description matches
itemDescription. - The item's seller matches
itemSeller. - The item's price matches
itemPrice. - The item's reserve matches
itemReserve.
Refer to the
solutionfolder for answers. -
Challenge
Item Repository Testing
Test the
ItemRepositoryusing Spring'sDataJpaTest.File: src/test/java/com/pluralsight/auction/ItemRepositoryTest.java
Task 1: Create a Test Item In the
testSaveAndFindmethod, instantiate anItemwith these parameters:- Name: "testItem"
- Description: "testDescription"
- Seller: "testSeller"
- Price: 100.0
- Reserve: 50.0
Task 2: Save the Test Item Persist the
Iteminstance using thesavemethod ofItemRepository. Assign the result back to theitemvariable.Task 3: Retrieve the Test Item Use the
findByIdmethod ofItemRepositoryto retrieve theItem. The argument should be the ID of the saveditem.Task 4: Assert the Retrieved Item
- Use the
assertTruemethod to assert that theOptional<Item>is not empty. - Assert that the retrieved item's name matches the original item's name using
assertEquals.
Note:
getmethod ofOptionalthrows aNoSuchElementExceptionifOptionalis empty. EnsureOptionalis not empty before usingget.Run the test using
gradle testin the terminal. Refer to thesolutionfolder for answers. -
Challenge
Item Controller Testing
This module focuses on testing the
ItemControllerclass usingMockMvcfor HTTP requests and Mockito for mockingItemRepository.File: src/test/java/com/pluralsight/auction/ItemControllerTest.java
Task 1: Create Test Item and Configure Mock Behavior In the
testListItemsmethod, create a testItemand aList<Item>containing it. ConfigureItemRepositoryto return this list whenfindAllis called.Task 2: Perform Request and Assert Model Use
MockMvcto perform a GET request to the root URL ("/"). Validate the response withandExpectto check:- HTTP status is OK.
- View name is "index".
- Model contains an attribute named "items".
- The "items" attribute matches the defined list.
Task 3: Perform Request and Assert View In
testListItemsView, set up the test item, list, and mock behavior as before. Perform a GET request to the root URL ("/"). This time, check:- HTTP status and view name as before.
- Response content contains "Auction Items".
- Response content includes the test item's name, description, seller, and price.
After completing these tasks, you should have two functional tests for
ItemController.Run the test using
gradle testin the terminal. Refer to thesolutionfolder for answers. -
Challenge
Spring Security Configuration
Setup Spring Security for the application, including HTTP security, password encoding, and user details service.
File: src/main/java/com/pluralsight/auction/SecurityConfig.java
Task 1: HTTP Security Configuration Define a
SecurityFilterChainbean infilterChainmethod, building aHttpSecurityinstance that:- Disables CSRF protection.
- Permits all requests to static resources and root URL ("/").
- Requires "ADMIN" role for "/admin" URL.
- Configures form-based login and logout with URLs "/login", "/login", and "/admin" respectively, permitting all requests.
- Sets logout request matcher to a new
AntPathRequestMatcherfor the "/logout" URL, permitting all requests.
Task 2: Password Encoder Configuration Define a
PasswordEncoderbean inpasswordEncodermethod, returning a newBCryptPasswordEncoderinstance.Task 3: User Details Service Configuration Define a
UserDetailsServicebean inuserDetailsServicemethod, creating aUserDetailsinstance for an admin user with:- Username: "admin"
- Password: "admin" (encoded with
PasswordEncoder) - Role: "ADMIN"
Return a new
InMemoryUserDetailsManagerwith the admin user.After these tasks, your application will be secured with Spring Security. Use
gradle bootrunin the terminal to run the application. Open the Simple Browser in VS Code to view it. The solution is in thesolutionfolder. If you have closed the Simple Web Browser you can reset the workspace by opening the Command Palette (Ctrl+Shift+P) and searching forReset Workspace Layout. -
Challenge
Admin Controller Testing
Now test the
AdminControllerclass usingMockMvcfor HTTP requests, Mockito for mockingItemRepository, and@WithMockUserto simulate a logged-in user.File: src/test/java/com/pluralsight/auction/AdminControllerTest.java
Task 1: Set Up Test Environment Annotate
AdminControllerTestclass with@SpringBootTestand@AutoConfigureMockMvc. Define fields forMockMvcandItemRepository, annotated with@Autowiredand@MockBeanrespectively.Task 2: Create a Test Item and Configure Mock Behavior In the
testListItemsmethod, create a testItemand aList<Item>containing it. ConfigureItemRepositoryto return this list whenfindAllis called.Task 3: Simulate a Logged-In User Annotate
testListItemswith@WithMockUser, setting username, password, and role to "admin", "admin", and "ADMIN" respectively.Task 4: Perform Request and Assert Model Use
MockMvcto perform a GET request to "/admin". UseandExpectto validate the response, checking:- HTTP status is OK.
- View name is "admin".
- Model contains an attribute named "items".
- The "items" attribute matches the defined list.
After completing these tasks, you will have a working test for
AdminController.To run the tests, type
gradle testin the terminal. Refer to thesolutionfolder for answers.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.