- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Extend Security and Testing in an Auction Application with Spring Framework 7
In this compact yet comprehensive Code Lab, you'll journey into the realms of application security and testing with the cutting-edge Spring Framework 7. Your hands-on project will revolve around an auction application, which you'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 7 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 step, you'll create a JUnit test for the
Itemclass.File:
src/test/java/com/pluralsight/auction/ItemTest.javaTask 1: Define Test Variables
In the
testItemmethod, define these variables:itemName: Set to"testItem".itemDescription: Set to"testDescription".itemSeller: Set to"testSeller".itemPrice: Set to100.0.itemReserve: Set to50.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.
To run the tests, type the command
./gradlew testin the Terminal. The solution can be found in thesolutionfolder. -
Challenge
Item Repository Testing
In this step, test the
ItemRepositoryusing Spring'sDataJpaTest.File:
src/test/java/com/pluralsight/auction/ItemRepositoryTest.javaTask 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.
info> Note:
getmethod ofOptionalthrows aNoSuchElementExceptionifOptionalis empty. EnsureOptionalis not empty before usingget.To run the tests, type the command
./gradlew testin the Terminal. The solution can be found in thesolutionfolder. - Name:
-
Challenge
Item Controller Testing
This step focuses on testing the
ItemControllerclass usingMockMvcfor HTTP requests and Mockito for mockingItemRepository.File:
src/test/java/com/pluralsight/auction/ItemControllerTest.javaTask 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.To run the tests, type the command
./gradlew testin the Terminal. The solution can be found in thesolutionfolder. - HTTP status is
-
Challenge
Spring Security Configuration
In this step, you will set up Spring Security for the application, including HTTP security, password encoding, and user details service.
File:
src/main/java/com/pluralsight/auction/SecurityConfig.javaTask 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 withPasswordEncoder) - Role:
"ADMIN"
Return a new
InMemoryUserDetailsManagerwith the admin user.To run view the application in the browser, first run the command
./gradlew bootrunin the Terminal and navigate to {{localhost:8080}}/admin. Also check out to make sure your other paths are working:/loginand/logout. The solution can be found in thesolutionfolder. -
Challenge
Admin Controller Testing
In this step, test the
AdminControllerclass usingMockMvcfor HTTP requests, Mockito for mockingItemRepository, and@WithMockUserto simulate a logged-in user.File:
src/test/java/com/pluralsight/auction/AdminControllerTest.javaTask 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 the command
./gradlew testin the Terminal. The solution can be found in thesolutionfolder. - HTTP status is
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.