- Lab
- 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.

Path Info
Table of Contents
-
Challenge
Item Class Testing
In this module you'll create a JUnit test for the
Item
class.File: src/test/java/com/pluralsight/auction/ItemTest.java
Task 1: Define Test Variables In the
testItem
method, 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
Item
in thetestItem
method.Task 3: Assert the Item's Properties In the
testItem
method, validate theItem
's properties usingassertEquals
statements. 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
solution
folder for answers. -
Challenge
Item Repository Testing
Test the
ItemRepository
using Spring'sDataJpaTest
.File: src/test/java/com/pluralsight/auction/ItemRepositoryTest.java
Task 1: Create a Test Item In the
testSaveAndFind
method, instantiate anItem
with these parameters:- Name: "testItem"
- Description: "testDescription"
- Seller: "testSeller"
- Price: 100.0
- Reserve: 50.0
Task 2: Save the Test Item Persist the
Item
instance using thesave
method ofItemRepository
. Assign the result back to theitem
variable.Task 3: Retrieve the Test Item Use the
findById
method ofItemRepository
to retrieve theItem
. The argument should be the ID of the saveditem
.Task 4: Assert the Retrieved Item
- Use the
assertTrue
method to assert that theOptional<Item>
is not empty. - Assert that the retrieved item's name matches the original item's name using
assertEquals
.
Note:
get
method ofOptional
throws aNoSuchElementException
ifOptional
is empty. EnsureOptional
is not empty before usingget
.Run the test using
gradle test
in the terminal. Refer to thesolution
folder for answers. -
Challenge
Item Controller Testing
This module focuses on testing the
ItemController
class usingMockMvc
for 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
testListItems
method, create a testItem
and aList<Item>
containing it. ConfigureItemRepository
to return this list whenfindAll
is called.Task 2: Perform Request and Assert Model Use
MockMvc
to perform a GET request to the root URL ("/"). Validate the response withandExpect
to 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 test
in the terminal. Refer to thesolution
folder 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
SecurityFilterChain
bean infilterChain
method, building aHttpSecurity
instance 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
AntPathRequestMatcher
for the "/logout" URL, permitting all requests.
Task 2: Password Encoder Configuration Define a
PasswordEncoder
bean inpasswordEncoder
method, returning a newBCryptPasswordEncoder
instance.Task 3: User Details Service Configuration Define a
UserDetailsService
bean inuserDetailsService
method, creating aUserDetails
instance for an admin user with:- Username: "admin"
- Password: "admin" (encoded with
PasswordEncoder
) - Role: "ADMIN"
Return a new
InMemoryUserDetailsManager
with the admin user.After these tasks, your application will be secured with Spring Security. Use
gradle bootrun
in the terminal to run the application. Open the Simple Browser in VS Code to view it. The solution is in thesolution
folder. 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
AdminController
class usingMockMvc
for HTTP requests, Mockito for mockingItemRepository
, and@WithMockUser
to simulate a logged-in user.File: src/test/java/com/pluralsight/auction/AdminControllerTest.java
Task 1: Set Up Test Environment Annotate
AdminControllerTest
class with@SpringBootTest
and@AutoConfigureMockMvc
. Define fields forMockMvc
andItemRepository
, annotated with@Autowired
and@MockBean
respectively.Task 2: Create a Test Item and Configure Mock Behavior In the
testListItems
method, create a testItem
and aList<Item>
containing it. ConfigureItemRepository
to return this list whenfindAll
is called.Task 3: Simulate a Logged-In User Annotate
testListItems
with@WithMockUser
, setting username, password, and role to "admin", "admin", and "ADMIN" respectively.Task 4: Perform Request and Assert Model Use
MockMvc
to perform a GET request to "/admin". UseandExpect
to 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 test
in the terminal. Refer to thesolution
folder for answers.
What's a lab?
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.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the author’s guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.