Featured resource
2025 Tech Upskilling Playbook
Tech Upskilling Playbook

Build future-ready tech teams and hit key business milestones with seven proven plays from industry leaders.

Check it out
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

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 platform
Lab Info
Level
Intermediate
Last updated
Jul 31, 2025
Duration
30m

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.
Table of Contents
  1. 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 the testItem method.

    Task 3: Assert the Item's Properties In the testItem method, validate the Item's properties using assertEquals 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.

  2. Challenge

    Item Repository Testing

    Test the ItemRepository using Spring's DataJpaTest.

    File: src/test/java/com/pluralsight/auction/ItemRepositoryTest.java

    Task 1: Create a Test Item In the testSaveAndFind method, instantiate an Item 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 the save method of ItemRepository. Assign the result back to the item variable.

    Task 3: Retrieve the Test Item Use the findById method of ItemRepository to retrieve the Item. The argument should be the ID of the saved item.

    Task 4: Assert the Retrieved Item

    • Use the assertTrue method to assert that the Optional<Item> is not empty.
    • Assert that the retrieved item's name matches the original item's name using assertEquals.

    Note: get method of Optional throws a NoSuchElementException if Optional is empty. Ensure Optional is not empty before using get.

    Run the test using gradle test in the terminal. Refer to the solution folder for answers.

  3. Challenge

    Item Controller Testing

    This module focuses on testing the ItemController class using MockMvc for HTTP requests and Mockito for mocking ItemRepository.

    File: src/test/java/com/pluralsight/auction/ItemControllerTest.java

    Task 1: Create Test Item and Configure Mock Behavior In the testListItems method, create a test Item and a List<Item> containing it. Configure ItemRepository to return this list when findAll is called.

    Task 2: Perform Request and Assert Model Use MockMvc to perform a GET request to the root URL ("/"). Validate the response with andExpect 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 the solution folder for answers.

  4. 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 in filterChain method, building a HttpSecurity 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 in passwordEncoder method, returning a new BCryptPasswordEncoder instance.

    Task 3: User Details Service Configuration Define a UserDetailsService bean in userDetailsService method, creating a UserDetails 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 the solution folder. If you have closed the Simple Web Browser you can reset the workspace by opening the Command Palette (Ctrl+Shift+P) and searching for Reset Workspace Layout.

  5. Challenge

    Admin Controller Testing

    Now test the AdminController class using MockMvc for HTTP requests, Mockito for mocking ItemRepository, 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 for MockMvc and ItemRepository, annotated with @Autowired and @MockBean respectively.

    Task 2: Create a Test Item and Configure Mock Behavior In the testListItems method, create a test Item and a List<Item> containing it. Configure ItemRepository to return this list when findAll 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". Use andExpect 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 the solution folder for answers.

About the author

Tom is a staff author at Pluralsight helping to develop Hands-On content. Tom's background in software development, UI/UX, and instructional design was developed over the years while working as a faculty member at the School of Computing at Weber State University in Utah, and continues to grow as he develops Projects and Labs for Pluralsight. When he's not creating content to allow learners to gain real-life experience, he enjoys spending time with his family.

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.

Get started with Pluralsight