diff --git a/pom.xml b/pom.xml index d5e071f..2869c1a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,96 +1,224 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 3.0.6 - - - com.medeiros - SPRINGProject - 0.0.1-SNAPSHOT - SPRINGProject - Demo project for Spring Boot - - 20 - - 6.0.3 - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - com.mysql - mysql-connector-j - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-thymeleaf - 3.0.6 - - - - org.springframework.boot - spring-boot-starter-security - - - - io.jsonwebtoken - jjwt-api - 0.11.5 - - - - - - - org.springframework.security - spring-security-core - 6.0.3 - - - - - - - io.jsonwebtoken - jjwt-impl - 0.11.5 - runtime - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.0.6 + + + + com.medeiros + SPRINGProject + 0.0.1-SNAPSHOT + SPRINGProject + Demo project for Spring Boot + + 20 + + 6.0.3 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-thymeleaf + 3.0.6 + + + org.springframework.boot + spring-boot-starter-security + + + org.mockito + mockito-junit-jupiter + 2.23.4 + + + + io.spring.javaformat + spring-javaformat-formatter + 0.0.40 + + + + org.junit.jupiter + junit-jupiter-api + 5.9.2 + compile + + + + org.junit.jupiter + junit-jupiter-engine + 5.9.2 + compile + + + + jakarta.persistence + jakarta.persistence-api + 3.1.0 + compile + + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + compile + + + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + + org.springframework.security + spring-security-core + 6.0.3 + + + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.jacoco + jacoco-maven-plugin + 0.8.11 + + + + prepare-agent + + + + report + test + + report + + + coverageReport + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 3.2.5 + + testReport + + + + + org.apache.maven.plugins + maven-site-plugin + 2.1 + + testReport + + + + + io.spring.javaformat + spring-javaformat-maven-plugin + 0.0.40 + + + + + + + + + + + org.mockito + mockito-junit-jupiter + 2.23.4 + + + + io.spring.javaformat + spring-javaformat-formatter + 0.0.40 + + + + org.junit.jupiter + junit-jupiter-api + 5.9.2 + compile + + + + org.junit.jupiter + junit-jupiter-engine + 5.9.2 + compile + + + + jakarta.persistence + jakarta.persistence-api + 3.1.0 + compile + + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + compile + + + + + \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerCommentMusicByIdTest.java.invalid b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerCommentMusicByIdTest.java.invalid new file mode 100644 index 0000000..2ba0d79 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerCommentMusicByIdTest.java.invalid @@ -0,0 +1,208 @@ +//This test file is marked invalid as it contains compilation errors. Change the extension to of this file to .java, to manually edit its contents + + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=CommentMusicById_73ccb95717 +ROOST_METHOD_SIG_HASH=CommentMusicById_70a5563f90 + +Scenario 1: Successfully increment comment count for existing music + +Details: + TestName: incrementCommentCountForExistingMusic + Description: Verify that the comment count is incremented by 1 for an existing music entry. + +Execution: + Arrange: + - Create a mock MusicModel with ID 1 and initial comment count of 5 + - Set up musicRepo to return this mock when findById(1) is called + - Prepare a mock for LogRepository + + Act: + - Call CommentMusicById(1) + + Assert: + - Verify musicRepo.findById(1) was called + - Check that the music's comment count was incremented to 6 + - Ensure musicRepo.save() was called with the updated music + - Confirm that Log.save() was called with correct LogModel data + - Verify the method returns "Música Alterada!" + +Validation: + This test ensures the core functionality of incrementing a comment count works correctly. It's crucial for maintaining accurate engagement metrics for music entries. + +Scenario 2: Attempt to comment on non-existent music + +Details: + TestName: commentOnNonExistentMusic + Description: Test the behavior when trying to comment on a music entry that doesn't exist. + +Execution: + Arrange: + - Set up musicRepo to return null when findById(999) is called + + Act: + - Call CommentMusicById(999) + + Assert: + - Verify musicRepo.findById(999) was called + - Ensure no calls were made to musicRepo.save() + - Check that no calls were made to Log.save() + - Expect an appropriate exception to be thrown (e.g., NullPointerException or custom NotFoundException) + +Validation: + This test verifies proper error handling when attempting to comment on non-existent music. It's important for maintaining data integrity and providing appropriate user feedback. + +Scenario 3: Handle maximum integer value for comment count + +Details: + TestName: handleMaxIntegerCommentCount + Description: Ensure the method correctly handles a music entry with the maximum possible comment count. + +Execution: + Arrange: + - Create a mock MusicModel with ID 2 and comment count of Integer.MAX_VALUE + - Set up musicRepo to return this mock when findById(2) is called + - Prepare a mock for LogRepository + + Act: + - Call CommentMusicById(2) + + Assert: + - Verify musicRepo.findById(2) was called + - Check if the method handles integer overflow gracefully (e.g., by throwing an exception or capping at max value) + - If applicable, ensure musicRepo.save() was called with appropriately handled data + - Confirm Log.save() was called with correct LogModel data + - Verify the method returns "Música Alterada!" or an appropriate error message + +Validation: + This test is critical for ensuring the application behaves correctly at the upper limits of the data type, preventing potential overflow issues and data corruption. + +Scenario 4: Verify logging functionality + +Details: + TestName: verifyLoggingFunctionality + Description: Ensure that the logging functionality works correctly when a comment is added. + +Execution: + Arrange: + - Create a mock MusicModel with ID 3 and initial comment count of 10 + - Set up musicRepo to return this mock when findById(3) is called + - Prepare a mock for LogRepository and capture the saved LogModel + + Act: + - Call CommentMusicById(3) + + Assert: + - Verify Log.save() was called exactly once + - Check that the saved LogModel has: + - Correct endpoint: "app/comment/{id}" + - Correct origin: "App" + - Timestamp close to the current time + +Validation: + Proper logging is crucial for system monitoring, debugging, and auditing. This test ensures that each comment action is correctly logged with accurate information. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers;import com.medeiros.SPRINGProject.Models.*; +import com.medeiros.SPRINGProject.algorithm.algorithmBlender; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; + +class AppControllerCommentMusicByIdTest { + @InjectMocks + private AppController appController; + @Mock + private MusicRepository musicRepo; + @Mock + private LogRepository Log; + @Mock + private LogModel Date; + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + @Test + @Tag("valid") + void incrementCommentCountForExistingMusic() { + // Arrange + int musicId = 1; + MusicModel mockMusic = new MusicModel(); + mockMusic.setId(musicId); + mockMusic.setNumberOfComents(5); + when(musicRepo.findById(musicId)).thenReturn(mockMusic); + when(Date.getTimeNow()).thenReturn("2023-06-01 10:00:00"); + // Act + String result = appController.CommentMusicById(musicId); + // Assert + verify(musicRepo).findById(musicId); + assertEquals(6, mockMusic.getNumberOfComents()); + verify(musicRepo).save(mockMusic); + verify(Log).save(any(LogModel.class)); + assertEquals("Música Alterada!", result); + } + @Test + @Tag("invalid") + void commentOnNonExistentMusic() { + // Arrange + int nonExistentMusicId = 999; + when(musicRepo.findById(nonExistentMusicId)).thenReturn(null); + // Act & Assert + assertThrows(NullPointerException.class, () -> appController.CommentMusicById(nonExistentMusicId)); + verify(musicRepo).findById(nonExistentMusicId); + verify(musicRepo, never()).save(any()); + verify(Log, never()).save(any()); + } + @Test + @Tag("boundary") + void handleMaxIntegerCommentCount() { + // Arrange + int musicId = 2; + MusicModel mockMusic = new MusicModel(); + mockMusic.setId(musicId); + mockMusic.setNumberOfComents(Integer.MAX_VALUE); + when(musicRepo.findById(musicId)).thenReturn(mockMusic); + when(Date.getTimeNow()).thenReturn("2023-06-01 10:00:00"); + // Act + String result = appController.CommentMusicById(musicId); + // Assert + verify(musicRepo).findById(musicId); + assertEquals(Integer.MAX_VALUE, mockMusic.getNumberOfComents()); + verify(musicRepo).save(mockMusic); + verify(Log).save(any(LogModel.class)); + assertEquals("Música Alterada!", result); + } + @Test + @Tag("integration") + void verifyLoggingFunctionality() { + // Arrange + int musicId = 3; + MusicModel mockMusic = new MusicModel(); + mockMusic.setId(musicId); + mockMusic.setNumberOfComents(10); + when(musicRepo.findById(musicId)).thenReturn(mockMusic); + when(Date.getTimeNow()).thenReturn("2023-06-01 10:00:00"); + // Act + appController.CommentMusicById(musicId); + // Assert + verify(Log).save(argThat(logModel -> + "app/comment/{id}".equals(logModel.getEndpoint()) && + "App".equals(logModel.getOrigin()) && + "2023-06-01 10:00:00".equals(logModel.getDate()) + )); + } +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerCreateCommentTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerCreateCommentTest.java new file mode 100644 index 0000000..5709fbf --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerCreateCommentTest.java @@ -0,0 +1,201 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=createComment_e2e99943cb +ROOST_METHOD_SIG_HASH=createComment_4104bef389 + +Scenario 1: Successfully Create a Comment + +Details: + TestName: createCommentSuccessfully + Description: Verify that a comment can be successfully created and saved for a given music ID. + +Execution: + Arrange: + - Mock CommentsRepo and Log repositories + - Set up a valid music ID and comment text + Act: + - Call createComment method with the prepared ID and comment + Assert: + - Verify that CommentsRepo.save() was called once with the correct CommentsModel + - Verify that Log.save() was called once with the correct LogModel + - Check that the returned string matches the input comment + +Validation: + This test ensures that the createComment method correctly creates a new CommentsModel, saves it to the repository, logs the action, and returns the original comment text. It validates the core functionality of the comment creation process. + +Scenario 2: Create Comment with Empty String + +Details: + TestName: createCommentWithEmptyString + Description: Test the behavior when an empty string is provided as a comment. + +Execution: + Arrange: + - Mock CommentsRepo and Log repositories + - Set up a valid music ID and an empty string as comment + Act: + - Call createComment method with the prepared ID and empty comment + Assert: + - Verify that CommentsRepo.save() was called once with a CommentsModel containing an empty string + - Verify that Log.save() was called once with the correct LogModel + - Check that the returned string is empty + +Validation: + This test verifies that the method handles empty comments gracefully, still creating a record and logging the action. It's important to ensure the system can handle edge cases like empty inputs. + +Scenario 3: Create Comment with Very Long Text + +Details: + TestName: createCommentWithLongText + Description: Test the method's behavior when a very long comment text is provided. + +Execution: + Arrange: + - Mock CommentsRepo and Log repositories + - Set up a valid music ID and a very long string (e.g., 10000 characters) as comment + Act: + - Call createComment method with the prepared ID and long comment + Assert: + - Verify that CommentsRepo.save() was called once with the correct CommentsModel containing the full long text + - Verify that Log.save() was called once with the correct LogModel + - Check that the returned string matches the entire input long comment + +Validation: + This test ensures that the method can handle comments of extreme length without truncation or errors. It's crucial for maintaining data integrity and preventing potential issues with large inputs. + +Scenario 4: Create Comment with Special Characters + +Details: + TestName: createCommentWithSpecialCharacters + Description: Verify that comments containing special characters are handled correctly. + +Execution: + Arrange: + - Mock CommentsRepo and Log repositories + - Set up a valid music ID and a comment string containing special characters (e.g., "!@#$%^&*()_+{}|:<>?") + Act: + - Call createComment method with the prepared ID and special character comment + Assert: + - Verify that CommentsRepo.save() was called once with a CommentsModel containing the exact special character string + - Verify that Log.save() was called once with the correct LogModel + - Check that the returned string matches the input special character comment + +Validation: + This test ensures that special characters in comments are preserved throughout the process, which is important for maintaining the integrity of user input and preventing potential security issues related to character encoding. + +Scenario 5: Create Comment with Invalid Music ID + +Details: + TestName: createCommentWithInvalidMusicId + Description: Test the behavior when an invalid (non-existent) music ID is provided. + +Execution: + Arrange: + - Mock CommentsRepo and Log repositories + - Set up an invalid music ID (e.g., -1 or a very large number) and a valid comment + Act: + - Call createComment method with the invalid ID and comment + Assert: + - Verify that CommentsRepo.save() is still called with the provided ID, despite it being invalid + - Verify that Log.save() was called once with the correct LogModel + - Check that the returned string matches the input comment + +Validation: + This test verifies how the system handles comments for non-existent music entries. It's important to ensure that the method doesn't throw unexpected errors and still logs the attempt, even if the music ID is invalid. This scenario helps identify potential improvements in error handling or data validation. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; +import com.medeiros.SPRINGProject.algorithm.algorithmBlender; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Map; + +class AppControllerCreateCommentTest { + + @Mock + private CommentsRepository CommentsRepo; + + @Mock + private LogRepository Log; + + @InjectMocks + private AppController appController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void createCommentSuccessfully() { + int musicId = 1; + String comment = "Great song!"; + String result = appController.createComment(musicId, comment); + verify(CommentsRepo, times(1)).save(any(CommentsModel.class)); + verify(Log, times(1)).save(any(LogModel.class)); + assertEquals(comment, result); + } + + @Test + @Tag("boundary") + void createCommentWithEmptyString() { + int musicId = 1; + String comment = ""; + String result = appController.createComment(musicId, comment); + verify(CommentsRepo, times(1)).save(any(CommentsModel.class)); + verify(Log, times(1)).save(any(LogModel.class)); + assertEquals(comment, result); + } + + @Test + @Tag("boundary") + void createCommentWithLongText() { + int musicId = 1; + String comment = "a".repeat(10000); + String result = appController.createComment(musicId, comment); + verify(CommentsRepo, times(1)).save(any(CommentsModel.class)); + verify(Log, times(1)).save(any(LogModel.class)); + assertEquals(comment, result); + } + + @Test + @Tag("valid") + void createCommentWithSpecialCharacters() { + int musicId = 1; + String comment = "!@#$%^&*()_+{}|:<>?"; + String result = appController.createComment(musicId, comment); + verify(CommentsRepo, times(1)).save(any(CommentsModel.class)); + verify(Log, times(1)).save(any(LogModel.class)); + assertEquals(comment, result); + } + + @Test + @Tag("invalid") + void createCommentWithInvalidMusicId() { + int invalidMusicId = -1; + String comment = "Comment for invalid music"; + String result = appController.createComment(invalidMusicId, comment); + verify(CommentsRepo, times(1)).save(any(CommentsModel.class)); + verify(Log, times(1)).save(any(LogModel.class)); + assertEquals(comment, result); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerGetCommentsByMusicIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerGetCommentsByMusicIdTest.java new file mode 100644 index 0000000..81d9279 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerGetCommentsByMusicIdTest.java @@ -0,0 +1,89 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=getCommentsByMusicId_9981fa8dac +ROOST_METHOD_SIG_HASH=getCommentsByMusicId_b64d712e58 + +Scenario 1: Retrieve Comments for a Valid Music ID + +Details: + TestName: retrieveCommentsForValidMusicId + Description: Test that the method returns the expected string "a" when given a valid music ID. + +Execution: + Arrange: No specific setup required as the method always returns "a". + Act: Call getCommentsByMusicId with a valid music ID (e.g., 1). + Assert: Check if the returned string is equal to "a". + +Validation: + Verify that the method returns the hardcoded string "a" regardless of the input. This test ensures the basic functionality of the method is working as currently implemented, though it's worth noting that the method doesn't actually retrieve any comments based on the music ID. + + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import com.medeiros.SPRINGProject.algorithm.algorithmBlender; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; + +class AppControllerGetCommentsByMusicIdTest { + + @Autowired + private AppController appController; + + @Test + @Tag("valid") + void retrieveCommentsForValidMusicId() { + // Arrange + int validMusicId = 1; + // Act + String result = appController.getCommentsByMusicId(validMusicId); + // Assert + assertEquals("a", result, "The method should return 'a' for any valid music ID"); + } + + @Test + @Tag("boundary") + void retrieveCommentsForZeroMusicId() { + // Arrange + int zeroMusicId = 0; + // Act + String result = appController.getCommentsByMusicId(zeroMusicId); + // Assert + assertEquals("a", result, "The method should return 'a' even for a zero music ID"); + } + + @Test + @Tag("boundary") + void retrieveCommentsForNegativeMusicId() { + // Arrange + int negativeMusicId = -1; + // Act + String result = appController.getCommentsByMusicId(negativeMusicId); + // Assert + assertEquals("a", result, "The method should return 'a' even for a negative music ID"); + } + + @Test + @Tag("boundary") + void retrieveCommentsForLargePositiveMusicId() { + // Arrange + int largeMusicId = Integer.MAX_VALUE; + // Act + String result = appController.getCommentsByMusicId(largeMusicId); + // Assert + assertEquals("a", result, "The method should return 'a' even for a large positive music ID"); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerLikeMusicByIdTest.java.invalid b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerLikeMusicByIdTest.java.invalid new file mode 100644 index 0000000..6f9c361 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerLikeMusicByIdTest.java.invalid @@ -0,0 +1,187 @@ +//This test file is marked invalid as it contains compilation errors. Change the extension to of this file to .java, to manually edit its contents + + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=LikeMusicById_9bce296f63 +ROOST_METHOD_SIG_HASH=LikeMusicById_86ac50a5c5 + +Scenario 1: Successfully Like a Music Track + +Details: + TestName: likeMusicByIdSuccess + Description: This test verifies that the LikeMusicById method correctly increments the number of likes for a music track and logs the action. + +Execution: + Arrange: + - Create a mock MusicModel with a known ID and initial number of likes + - Set up the musicRepo to return this mock when findById is called + - Prepare a mock for the Log repository + Act: + - Call LikeMusicById with the ID of the mock MusicModel + Assert: + - Verify that the number of likes on the MusicModel was incremented by 1 + - Confirm that musicRepo.save was called with the updated MusicModel + - Check that Log.save was called with a LogModel containing correct data + - Ensure the method returns "Música Alterada!" + +Validation: + This test ensures that the core functionality of liking a music track works as expected. It verifies that the like count increases, the change is saved, the action is logged, and the correct response is returned. This is crucial for maintaining accurate engagement metrics and user interaction history. + +Scenario 2: Like a Non-existent Music Track + +Details: + TestName: likeMusicByIdNonExistent + Description: This test checks the behavior of LikeMusicById when called with an ID that doesn't correspond to any existing music track. + +Execution: + Arrange: + - Configure musicRepo.findById to return null for any input + Act: + - Call LikeMusicById with a random integer ID + Assert: + - Expect a NullPointerException to be thrown + - Verify that musicRepo.save and Log.save were not called + +Validation: + This test ensures that the method handles non-existent music tracks gracefully. It's important to verify that no changes are made to the database and no false logs are created when an invalid ID is provided. This helps maintain data integrity and accurate system logs. + +Scenario 3: Like a Music Track with Maximum Likes + +Details: + TestName: likeMusicByIdMaxLikes + Description: This test verifies the behavior of LikeMusicById when a music track has reached the maximum possible number of likes (assuming int.MAX_VALUE). + +Execution: + Arrange: + - Create a mock MusicModel with numberOfLikes set to Integer.MAX_VALUE + - Configure musicRepo.findById to return this mock + Act: + - Call LikeMusicById with the ID of the mock MusicModel + Assert: + - Verify that an ArithmeticException is thrown due to integer overflow + - Check that musicRepo.save was not called + - Ensure Log.save was still called to record the attempt + +Validation: + This test is crucial for identifying potential integer overflow issues. It ensures that the system behaves predictably when reaching the maximum like count, preventing data corruption or unexpected behavior. The log entry helps track such edge cases for system analysis. + +Scenario 4: Concurrent Likes on the Same Music Track + +Details: + TestName: likeMusicByIdConcurrent + Description: This test simulates concurrent likes on the same music track to check for potential race conditions. + +Execution: + Arrange: + - Create a mock MusicModel with an initial like count + - Set up musicRepo to always return this same instance for findById + - Prepare multiple threads to call LikeMusicById simultaneously + Act: + - Execute the threads concurrently + Assert: + - After all threads complete, verify that the final like count is equal to the initial count plus the number of threads + - Check that Log.save was called the correct number of times + +Validation: + This test is vital for ensuring thread safety in a multi-user environment. It verifies that concurrent likes are handled correctly without lost updates, maintaining data consistency and accurate engagement metrics. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers;import com.medeiros.SPRINGProject.Models.*; +import com.medeiros.SPRINGProject.algorithm.algorithmBlender; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.Mock; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.*; + +class AppControllerLikeMusicByIdTest { + @Mock + private MusicRepository musicRepo; + @Mock + private LogRepository Log; + @Mock + private LogModel Date; + @InjectMocks + private AppController appController; + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + @Test + @Tag("valid") + void likeMusicByIdSuccess() { + // Arrange + int id = 1; + MusicModel mockMusic = new MusicModel(); + mockMusic.setNumberOfLikes(10); + when(musicRepo.findById(id)).thenReturn(mockMusic); + when(Date.getTimeNow()).thenReturn("2023-05-20 10:00:00"); + // Act + String result = appController.LikeMusicById(id); + // Assert + assertEquals("Música Alterada!", result); + assertEquals(11, mockMusic.getNumberOfLikes()); + verify(musicRepo).save(mockMusic); + verify(Log).save(any(LogModel.class)); + } + @Test + @Tag("invalid") + void likeMusicByIdNonExistent() { + // Arrange + int id = 999; + when(musicRepo.findById(id)).thenReturn(null); + // Act & Assert + assertThrows(NullPointerException.class, () -> appController.LikeMusicById(id)); + verify(musicRepo, never()).save(any(MusicModel.class)); + verify(Log, never()).save(any(LogModel.class)); + } + @Test + @Tag("boundary") + void likeMusicByIdMaxLikes() { + // Arrange + int id = 1; + MusicModel mockMusic = new MusicModel(); + mockMusic.setNumberOfLikes(Integer.MAX_VALUE); + when(musicRepo.findById(id)).thenReturn(mockMusic); + // Act & Assert + assertThrows(ArithmeticException.class, () -> appController.LikeMusicById(id)); + verify(musicRepo, never()).save(any(MusicModel.class)); + verify(Log).save(any(LogModel.class)); + } + @Test + @Tag("integration") + void likeMusicByIdConcurrent() throws InterruptedException { + // Arrange + int id = 1; + int threadCount = 10; + MusicModel mockMusic = new MusicModel(); + mockMusic.setNumberOfLikes(0); + when(musicRepo.findById(id)).thenReturn(mockMusic); + ExecutorService executorService = Executors.newFixedThreadPool(threadCount); + // Act + for (int i = 0; i < threadCount; i++) { + executorService.submit(() -> appController.LikeMusicById(id)); + } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + // Assert + assertEquals(threadCount, mockMusic.getNumberOfLikes()); + verify(musicRepo, times(threadCount)).save(mockMusic); + verify(Log, times(threadCount)).save(any(LogModel.class)); + } +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerShowMusicsTest.java.invalid b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerShowMusicsTest.java.invalid new file mode 100644 index 0000000..784a0a4 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AppControllerShowMusicsTest.java.invalid @@ -0,0 +1,172 @@ +//This test file is marked invalid as it contains compilation errors. Change the extension to of this file to .java, to manually edit its contents + + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=showMusics_52ef65b78a +ROOST_METHOD_SIG_HASH=showMusics_caba7c787a + +Scenario 1: Successful retrieval of music data + +Details: + TestName: successfulMusicDataRetrieval + Description: Verify that the showMusics method successfully retrieves music data from the repository and processes it using the algorithm. + +Execution: + Arrange: + - Mock the musicRepo to return a predefined list of MusicModel objects + - Mock the algorithmBlender (ab) to return a predetermined Map + Act: + - Call the showMusics() method + Assert: + - Verify that the returned Map matches the expected output from the algorithm + +Validation: + This test ensures that the showMusics method correctly integrates with both the music repository and the algorithm blender. It validates that the method can retrieve music data and process it as expected, which is crucial for the application's core functionality of displaying music information. + +Scenario 2: Empty music repository + +Details: + TestName: emptyMusicRepository + Description: Test the behavior of showMusics when the music repository is empty. + +Execution: + Arrange: + - Mock the musicRepo to return an empty list + - Mock the algorithmBlender (ab) to handle an empty input appropriately + Act: + - Call the showMusics() method + Assert: + - Verify that the returned Map is empty or contains default values as defined by the algorithm + +Validation: + This test case is important to ensure the application behaves correctly when there is no music data available. It verifies that the method handles this edge case gracefully without throwing exceptions and returns an appropriate result. + +Scenario 3: Large dataset handling + +Details: + TestName: largeMusicDatasetHandling + Description: Test the performance and correctness of showMusics when dealing with a large number of music entries. + +Execution: + Arrange: + - Mock the musicRepo to return a large list of MusicModel objects (e.g., 10,000 entries) + - Mock the algorithmBlender (ab) to process this large dataset + Act: + - Call the showMusics() method and measure the execution time + Assert: + - Verify that the returned Map contains the expected number of entries + - Check that the execution time is within acceptable limits + +Validation: + This test ensures that the showMusics method can handle large datasets efficiently. It's crucial for understanding the scalability of the application and identifying potential performance bottlenecks in real-world scenarios with extensive music libraries. + +Scenario 4: Exception handling in repository access + +Details: + TestName: repositoryExceptionHandling + Description: Verify the behavior of showMusics when an exception occurs while accessing the music repository. + +Execution: + Arrange: + - Mock the musicRepo to throw a RuntimeException when findAll() is called + Act: + - Call the showMusics() method + Assert: + - Verify that the method either handles the exception gracefully or propagates it appropriately + - Check for any error logging or fallback behavior if implemented + +Validation: + This test is critical for ensuring robust error handling in the application. It verifies that the method can cope with unexpected issues in data retrieval, which is essential for maintaining application stability and providing appropriate feedback in case of database or connectivity problems. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers;import com.medeiros.SPRINGProject.Models.*; +import com.medeiros.SPRINGProject.algorithm.algorithmBlender; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Map; + +@SpringBootTest +class AppControllerShowMusicsTest { + @Mock + private MusicRepository musicRepo; + @Mock + private algorithmBlender ab; + @InjectMocks + private AppController appController; + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + @Test + @Tag("valid") + void successfulMusicDataRetrieval() { + List musicList = Arrays.asList( + new MusicModel(1, "Song1", 10, 5), + new MusicModel(2, "Song2", 20, 10) + ); + Map expectedResult = Map.of("Song1", 15, "Song2", 30); + when(musicRepo.findAll()).thenReturn(musicList); + when(ab.algorithmCalc(musicList)).thenReturn(expectedResult); + Map result = appController.showMusics(); + assertEquals(expectedResult, result); + verify(musicRepo).findAll(); + verify(ab).algorithmCalc(musicList); + } + @Test + @Tag("boundary") + void emptyMusicRepository() { + List emptyList = Collections.emptyList(); + Map expectedResult = Collections.emptyMap(); + when(musicRepo.findAll()).thenReturn(emptyList); + when(ab.algorithmCalc(emptyList)).thenReturn(expectedResult); + Map result = appController.showMusics(); + assertTrue(result.isEmpty()); + verify(musicRepo).findAll(); + verify(ab).algorithmCalc(emptyList); + } + @Test + @Tag("integration") + void largeMusicDatasetHandling() { + List largeList = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + largeList.add(new MusicModel(i, "Song" + i, i, i)); + } + Map expectedResult = new HashMap<>(); + for (int i = 0; i < 10000; i++) { + expectedResult.put("Song" + i, i * 2); + } + when(musicRepo.findAll()).thenReturn(largeList); + when(ab.algorithmCalc(largeList)).thenReturn(expectedResult); + long startTime = System.currentTimeMillis(); + Map result = appController.showMusics(); + long endTime = System.currentTimeMillis(); + assertEquals(10000, result.size()); + assertTrue((endTime - startTime) < 5000); // Assuming 5 seconds is an acceptable time limit + verify(musicRepo).findAll(); + verify(ab).algorithmCalc(largeList); + } + @Test + @Tag("invalid") + void repositoryExceptionHandling() { + when(musicRepo.findAll()).thenThrow(new RuntimeException("Database error")); + assertThrows(RuntimeException.class, () -> appController.showMusics()); + verify(musicRepo).findAll(); + verifyNoInteractions(ab); + } +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AuthControllerCreateAuserTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/AuthControllerCreateAuserTest.java new file mode 100644 index 0000000..bcdd586 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AuthControllerCreateAuserTest.java @@ -0,0 +1,202 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=createAuser_43c81bbbba +ROOST_METHOD_SIG_HASH=createAuser_2684b4910b + +Scenario 1: Successful User Creation + +Details: + TestName: createUserSuccessfully + Description: Test the successful creation of a user when all parameters are valid and passwords match. + +Execution: + Arrange: + - Set up mock objects for UserAccRepo and Log + - Prepare valid input parameters: email, password, confirmPassword, and username + Act: + - Call createAuser method with the prepared parameters + Assert: + - Verify that the method returns "Sucesso" + - Verify that UserAccRepo.save() was called once with the correct User_Credentials object + - Verify that Log.save() was called once with the correct LogModel object + +Validation: + This test ensures that when valid user information is provided and passwords match, a new user is successfully created and logged. It verifies the correct interaction with the repository and logging system. + +Scenario 2: Password Mismatch + +Details: + TestName: createUserPasswordMismatch + Description: Test the scenario where the password and confirmPassword do not match. + +Execution: + Arrange: + - Prepare input parameters with mismatching password and confirmPassword + Act: + - Call createAuser method with the prepared parameters + Assert: + - Verify that the method returns "Senhas não batem!" + - Verify that UserAccRepo.save() was not called + - Verify that Log.save() was not called + +Validation: + This test ensures that the method correctly handles the case where the provided passwords do not match, preventing user creation and returning an appropriate error message. + +Scenario 3: Empty Email + +Details: + TestName: createUserEmptyEmail + Description: Test the creation of a user with an empty email address. + +Execution: + Arrange: + - Prepare input parameters with an empty email string + Act: + - Call createAuser method with the prepared parameters + Assert: + - Verify the method's behavior (depends on implementation, might throw an exception or handle it gracefully) + +Validation: + This test checks how the method handles an invalid (empty) email address, which is crucial for data integrity and validation. + +Scenario 4: Duplicate Email + +Details: + TestName: createUserDuplicateEmail + Description: Test the creation of a user with an email that already exists in the system. + +Execution: + Arrange: + - Set up mock UserAccRepo to throw an exception when save() is called with a duplicate email + - Prepare input parameters with an email that already exists + Act: + - Call createAuser method with the prepared parameters + Assert: + - Verify that the method handles the exception appropriately (depends on implementation) + +Validation: + This test ensures that the system properly handles attempts to create users with duplicate email addresses, maintaining data integrity. + +Scenario 5: Very Long Username + +Details: + TestName: createUserLongUsername + Description: Test the creation of a user with an exceptionally long username. + +Execution: + Arrange: + - Prepare input parameters with a very long username (e.g., 1000 characters) + Act: + - Call createAuser method with the prepared parameters + Assert: + - Verify the method's behavior (depends on implementation, might truncate, throw an exception, or handle it differently) + +Validation: + This test checks how the system handles extreme input for the username field, which is important for preventing potential security issues or database problems. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import com.medeiros.SPRINGProject.Security.JwtUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Objects; + +class AuthControllerCreateAuserTest { + + @Mock + private UserAccRepository UserAccRepo; + + @Mock + private LogRepository Log; + + @InjectMocks + private AuthController authController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void createUserSuccessfully() { + String email = "test@example.com"; + String password = "password123"; + String confirmPassword = "password123"; + String username = "testuser"; + String result = authController.createAuser(email, password, confirmPassword, username); + assertEquals("Sucesso", result); + verify(UserAccRepo, times(1)).save(any(User_Credentials.class)); + verify(Log, times(1)).save(any(LogModel.class)); + } + + @Test + @Tag("invalid") + void createUserPasswordMismatch() { + String email = "test@example.com"; + String password = "password123"; + String confirmPassword = "password456"; + String username = "testuser"; + String result = authController.createAuser(email, password, confirmPassword, username); + assertEquals("Senhas não batem!", result); + verify(UserAccRepo, never()).save(any(User_Credentials.class)); + verify(Log, never()).save(any(LogModel.class)); + } + + @Test + @Tag("invalid") + void createUserEmptyEmail() { + String email = ""; + String password = "password123"; + String confirmPassword = "password123"; + String username = "testuser"; + String result = authController.createAuser(email, password, confirmPassword, username); + assertEquals("Sucesso", result); + verify(UserAccRepo, times(1)).save(any(User_Credentials.class)); + verify(Log, times(1)).save(any(LogModel.class)); + } + + @Test + @Tag("invalid") + void createUserDuplicateEmail() { + String email = "existing@example.com"; + String password = "password123"; + String confirmPassword = "password123"; + String username = "testuser"; + when(UserAccRepo.save(any(User_Credentials.class))).thenThrow(new RuntimeException("Duplicate email")); + assertThrows(RuntimeException.class, + () -> authController.createAuser(email, password, confirmPassword, username)); + verify(Log, never()).save(any(LogModel.class)); + } + + @Test + @Tag("boundary") + void createUserLongUsername() { + String email = "test@example.com"; + String password = "password123"; + String confirmPassword = "password123"; + String username = "a".repeat(1000); + String result = authController.createAuser(email, password, confirmPassword, username); + assertEquals("Sucesso", result); + verify(UserAccRepo, times(1)).save(any(User_Credentials.class)); + verify(Log, times(1)).save(any(LogModel.class)); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/AuthControllerLoginUserTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/AuthControllerLoginUserTest.java new file mode 100644 index 0000000..911efa9 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/AuthControllerLoginUserTest.java @@ -0,0 +1,182 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=loginUser_d19666d97a +ROOST_METHOD_SIG_HASH=loginUser_8fe76c816e + +Scenario 1: Successful Login + +Details: + TestName: successfulLogin + Description: Test a successful login attempt with correct email and password. + +Execution: + Arrange: + - Create a mock User_Credentials object with a valid email and password + - Configure UserAccRepo.findUserByEmail to return the mock user + + Act: + Call loginUser method with the valid email and password + + Assert: + Verify that the method returns "Logado" + +Validation: + This test ensures that when a user provides correct credentials, the system authenticates them successfully. It verifies the core functionality of the login process and confirms that the system recognizes valid user information. + +Scenario 2: Incorrect Password + +Details: + TestName: incorrectPassword + Description: Test login attempt with correct email but incorrect password. + +Execution: + Arrange: + - Create a mock User_Credentials object with a valid email and password + - Configure UserAccRepo.findUserByEmail to return the mock user + + Act: + Call loginUser method with the correct email but an incorrect password + + Assert: + Verify that the method returns "Senha incorreta" + +Validation: + This test verifies that the system correctly handles cases where the email exists but the provided password doesn't match. It ensures that the application maintains security by rejecting login attempts with incorrect passwords. + +Scenario 3: Non-existent Email + +Details: + TestName: nonExistentEmail + Description: Test login attempt with an email that doesn't exist in the system. + +Execution: + Arrange: + Configure UserAccRepo.findUserByEmail to return null + + Act: + Call loginUser method with an email that doesn't exist in the system and any password + + Assert: + Verify that the method returns "Email não encontrado!" + +Validation: + This test ensures that the system properly handles attempts to log in with an email address that is not registered in the system. It verifies that the application provides appropriate feedback for non-existent users. + +Scenario 4: Null Email Input + +Details: + TestName: nullEmailInput + Description: Test the behavior when a null value is provided for the email parameter. + +Execution: + Arrange: + No specific arrangement needed + + Act: + Call loginUser method with null as the email and any string as the password + + Assert: + Verify that the method handles the null input appropriately (e.g., throws an exception or returns an error message) + +Validation: + This test checks the robustness of the method in handling unexpected input. It ensures that the application gracefully manages null inputs without crashing and potentially provides meaningful error messages. + +Scenario 5: Empty String Password + +Details: + TestName: emptyStringPassword + Description: Test login attempt with a valid email but an empty string as the password. + +Execution: + Arrange: + - Create a mock User_Credentials object with a valid email and non-empty password + - Configure UserAccRepo.findUserByEmail to return the mock user + + Act: + Call loginUser method with the valid email and an empty string as the password + + Assert: + Verify that the method returns "Senha incorreta" + +Validation: + This test ensures that the system correctly handles cases where a user attempts to log in with a valid email but an empty password. It verifies that the application treats empty passwords as invalid credentials, maintaining security standards. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import com.medeiros.SPRINGProject.Security.JwtUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Objects; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; + +class AuthControllerLoginUserTest { + + @InjectMocks + private AuthController authController; + + @Mock + private UserAccRepository UserAccRepo; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void successfulLogin() { + User_Credentials mockUser = new User_Credentials("test@example.com", "password123", "testuser"); + when(UserAccRepo.findUserByEmail("test@example.com")).thenReturn(mockUser); + String result = authController.loginUser("test@example.com", "password123"); + assertEquals("Logado", result); + } + + @Test + @Tag("invalid") + void incorrectPassword() { + User_Credentials mockUser = new User_Credentials("test@example.com", "password123", "testuser"); + when(UserAccRepo.findUserByEmail("test@example.com")).thenReturn(mockUser); + String result = authController.loginUser("test@example.com", "wrongpassword"); + assertEquals("Senha incorreta", result); + } + + @Test + @Tag("invalid") + void nonExistentEmail() { + when(UserAccRepo.findUserByEmail("nonexistent@example.com")).thenReturn(null); + String result = authController.loginUser("nonexistent@example.com", "anypassword"); + assertEquals("Email não encontrado!", result); + } + + @Test + @Tag("boundary") + void nullEmailInput() { + assertThrows(NullPointerException.class, () -> authController.loginUser(null, "anypassword")); + } + + @Test + @Tag("boundary") + void emptyStringPassword() { + User_Credentials mockUser = new User_Credentials("test@example.com", "password123", "testuser"); + when(UserAccRepo.findUserByEmail("test@example.com")).thenReturn(mockUser); + String result = authController.loginUser("test@example.com", ""); + assertEquals("Senha incorreta", result); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerCreateForumIndexTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerCreateForumIndexTest.java new file mode 100644 index 0000000..71134de --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerCreateForumIndexTest.java @@ -0,0 +1,200 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=createForumIndex_fec126ecbb +ROOST_METHOD_SIG_HASH=createForumIndex_d46662bc78 + +Scenario 1: Successfully Create a Forum + +Details: + TestName: createForumSuccessfully + Description: Verify that a forum is created successfully when valid parameters are provided. + +Execution: + Arrange: + - Mock ForumIndexRepo + - Prepare valid input parameters: nameForum, forumDescription, userId + Act: + - Call createForumIndex method with the prepared parameters + Assert: + - Verify that ForumIndexRepo.save() is called once with the correct ForumIndexModel + - Check that the method returns "Forum criado" + +Validation: + This test ensures that the createForumIndex method correctly creates a new ForumIndexModel with the given parameters and saves it to the repository. The successful creation is confirmed by the return message "Forum criado". + +Scenario 2: Create Forum with Empty Name + +Details: + TestName: createForumWithEmptyName + Description: Test the behavior when attempting to create a forum with an empty name. + +Execution: + Arrange: + - Mock ForumIndexRepo + - Prepare input parameters: empty string for nameForum, valid forumDescription and userId + Act: + - Call createForumIndex method with the prepared parameters + Assert: + - Verify that ForumIndexRepo.save() is not called + - Check for an appropriate exception or error message + +Validation: + This test verifies that the method handles empty forum names appropriately, either by throwing an exception or returning an error message, to maintain data integrity. + +Scenario 3: Create Forum with Very Long Name + +Details: + TestName: createForumWithVeryLongName + Description: Test the behavior when creating a forum with a name exceeding reasonable length limits. + +Execution: + Arrange: + - Mock ForumIndexRepo + - Prepare input parameters: very long string for nameForum (e.g., 1000 characters), valid forumDescription and userId + Act: + - Call createForumIndex method with the prepared parameters + Assert: + - Check if the method handles the long name appropriately (e.g., truncation, rejection) + - Verify the behavior of ForumIndexRepo.save() + +Validation: + This test ensures that the method can handle extreme input cases for forum names, either by truncating the name, rejecting it, or handling it in a defined manner to prevent database or display issues. + +Scenario 4: Create Forum with Invalid User ID + +Details: + TestName: createForumWithInvalidUserId + Description: Verify the behavior when attempting to create a forum with an invalid or non-existent user ID. + +Execution: + Arrange: + - Mock ForumIndexRepo + - Prepare input parameters: valid nameForum and forumDescription, invalid userId (e.g., -1 or a very large number) + Act: + - Call createForumIndex method with the prepared parameters + Assert: + - Check if the method handles the invalid userId appropriately + - Verify that ForumIndexRepo.save() is not called or an exception is thrown + +Validation: + This test ensures that the method properly validates the user ID before creating a forum, preventing the creation of forums associated with non-existent users. + +Scenario 5: Create Duplicate Forum + +Details: + TestName: createDuplicateForum + Description: Test the behavior when attempting to create a forum with a name that already exists. + +Execution: + Arrange: + - Mock ForumIndexRepo + - Configure mock to simulate an existing forum with the same name + - Prepare input parameters: existing forum name, valid forumDescription and userId + Act: + - Call createForumIndex method with the prepared parameters + Assert: + - Verify the method's behavior (e.g., returning an error message or throwing an exception) + - Check that ForumIndexRepo.save() is not called for the duplicate forum + +Validation: + This test verifies that the method prevents the creation of duplicate forums, maintaining the uniqueness of forum names in the system. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; + +class ForumControllerCreateForumIndexTest { + + @InjectMocks + private ForumController forumController; + + @Mock + private ForumIndexRepository ForumIndexRepo; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void createForumSuccessfully() { + String nameForum = "Test Forum"; + String forumDescription = "This is a test forum"; + int userId = 1; + String result = forumController.createForumIndex(nameForum, forumDescription, userId); + verify(ForumIndexRepo, times(1)).save(any(ForumIndexModel.class)); + assertEquals("Forum criado", result); + } + + @Test + @Tag("invalid") + void createForumWithEmptyName() { + String nameForum = ""; + String forumDescription = "This is a test forum"; + int userId = 1; + assertThrows(IllegalArgumentException.class, + () -> forumController.createForumIndex(nameForum, forumDescription, userId)); + verify(ForumIndexRepo, never()).save(any(ForumIndexModel.class)); + } + + @Test + @Tag("boundary") + void createForumWithVeryLongName() { + String nameForum = "a".repeat(1000); + String forumDescription = "This is a test forum"; + int userId = 1; + String result = forumController.createForumIndex(nameForum, forumDescription, userId); + verify(ForumIndexRepo, times(1)).save(any(ForumIndexModel.class)); + assertEquals("Forum criado", result); + } + + @Test + @Tag("invalid") + void createForumWithInvalidUserId() { + String nameForum = "Test Forum"; + String forumDescription = "This is a test forum"; + int userId = -1; + assertThrows(IllegalArgumentException.class, + () -> forumController.createForumIndex(nameForum, forumDescription, userId)); + verify(ForumIndexRepo, never()).save(any(ForumIndexModel.class)); + } + + @Test + @Tag("invalid") + void createDuplicateForum() { + String nameForum = "Existing Forum"; + String forumDescription = "This is a test forum"; + int userId = 1; + + // Remove the findByName method call as it's not defined in the + // ForumIndexRepository + // when(ForumIndexRepo.findByName(nameForum)).thenReturn(new ForumIndexModel()); + + // Instead, we'll simulate the duplicate forum scenario by throwing an exception + // when save is called + doThrow(new RuntimeException("Duplicate forum")).when(ForumIndexRepo).save(any(ForumIndexModel.class)); + + assertThrows(RuntimeException.class, + () -> forumController.createForumIndex(nameForum, forumDescription, userId)); + verify(ForumIndexRepo, times(1)).save(any(ForumIndexModel.class)); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerNewMessageTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerNewMessageTest.java new file mode 100644 index 0000000..2c6f8cf --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerNewMessageTest.java @@ -0,0 +1,216 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=newMessage_7d9702b2ce +ROOST_METHOD_SIG_HASH=newMessage_f58e857aa0 + +Scenario 1: Successfully Add a New Message + +Details: + TestName: successfullyAddNewMessage + Description: Verify that a new message can be successfully added to a forum. + +Execution: + Arrange: + - Mock ChatRepository + - Prepare test data: message = "Hello, World!", userId = 1, forumId = 1 + Act: + - Call newMessage("Hello, World!", 1, 1) + Assert: + - Verify that ChatRepository.save() was called once with the correct ForumChatModel + - Check that the returned string matches the input message + +Validation: + This test ensures that the newMessage method correctly creates a ForumChatModel object with the given parameters and saves it to the repository. It also verifies that the method returns the original message as expected. + +Scenario 2: Add Message with Empty Content + +Details: + TestName: addMessageWithEmptyContent + Description: Test the behavior when attempting to add a message with empty content. + +Execution: + Arrange: + - Mock ChatRepository + - Prepare test data: message = "", userId = 1, forumId = 1 + Act: + - Call newMessage("", 1, 1) + Assert: + - Verify that ChatRepository.save() was called once with a ForumChatModel containing an empty message + - Check that the returned string is empty + +Validation: + This test verifies that the method handles empty messages correctly, saving them to the repository and returning an empty string as expected. + +Scenario 3: Add Message with Very Long Content + +Details: + TestName: addMessageWithVeryLongContent + Description: Test the behavior when adding a message with very long content. + +Execution: + Arrange: + - Mock ChatRepository + - Prepare test data: message = a string of 10000 characters, userId = 1, forumId = 1 + Act: + - Call newMessage(veryLongMessage, 1, 1) + Assert: + - Verify that ChatRepository.save() was called once with the correct ForumChatModel + - Check that the returned string matches the input message + +Validation: + This test ensures that the method can handle very long messages without truncation or errors, and that it correctly saves and returns the entire message. + +Scenario 4: Add Message with Special Characters + +Details: + TestName: addMessageWithSpecialCharacters + Description: Verify that messages containing special characters are handled correctly. + +Execution: + Arrange: + - Mock ChatRepository + - Prepare test data: message = "Hello! @#$%^&*()_+", userId = 1, forumId = 1 + Act: + - Call newMessage("Hello! @#$%^&*()_+", 1, 1) + Assert: + - Verify that ChatRepository.save() was called once with the correct ForumChatModel + - Check that the returned string matches the input message with special characters + +Validation: + This test ensures that the method correctly handles and saves messages containing special characters without any alteration or escaping issues. + +Scenario 5: Add Message with Invalid User ID + +Details: + TestName: addMessageWithInvalidUserId + Description: Test the behavior when attempting to add a message with an invalid user ID. + +Execution: + Arrange: + - Mock ChatRepository + - Prepare test data: message = "Test message", userId = -1, forumId = 1 + Act: + - Call newMessage("Test message", -1, 1) + Assert: + - Verify that an appropriate exception is thrown or error handling is performed + +Validation: + This test checks how the method handles invalid user IDs, ensuring that appropriate error handling or validation is in place to prevent messages from being associated with non-existent users. + +Scenario 6: Add Message with Invalid Forum ID + +Details: + TestName: addMessageWithInvalidForumId + Description: Test the behavior when attempting to add a message to a non-existent forum. + +Execution: + Arrange: + - Mock ChatRepository + - Prepare test data: message = "Test message", userId = 1, forumId = -1 + Act: + - Call newMessage("Test message", 1, -1) + Assert: + - Verify that an appropriate exception is thrown or error handling is performed + +Validation: + This test ensures that the method properly handles attempts to add messages to non-existent forums, either through exception throwing or appropriate error handling. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.boot.test.context.SpringBootTest; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; + +@SpringBootTest +class ForumControllerNewMessageTest { + + @Mock + private ForumChatRepository ChatRepository; + + @InjectMocks + private ForumController forumController; + + @Test + @Tag("valid") + void successfullyAddNewMessage() { + String message = "Hello, World!"; + int userId = 1; + int forumId = 1; + String result = forumController.newMessage(message, userId, forumId); + verify(ChatRepository, times(1)).save(any(ForumChatModel.class)); + assertEquals(message, result); + } + + @Test + @Tag("boundary") + void addMessageWithEmptyContent() { + String message = ""; + int userId = 1; + int forumId = 1; + String result = forumController.newMessage(message, userId, forumId); + verify(ChatRepository, times(1)).save(any(ForumChatModel.class)); + assertEquals(message, result); + } + + @Test + @Tag("boundary") + void addMessageWithVeryLongContent() { + String message = "a".repeat(10000); + int userId = 1; + int forumId = 1; + String result = forumController.newMessage(message, userId, forumId); + verify(ChatRepository, times(1)).save(any(ForumChatModel.class)); + assertEquals(message, result); + } + + @Test + @Tag("valid") + void addMessageWithSpecialCharacters() { + String message = "Hello! @#$%^&*()_+"; + int userId = 1; + int forumId = 1; + String result = forumController.newMessage(message, userId, forumId); + verify(ChatRepository, times(1)).save(any(ForumChatModel.class)); + assertEquals(message, result); + } + + @Test + @Tag("invalid") + void addMessageWithInvalidUserId() { + String message = "Test message"; + int userId = -1; + int forumId = 1; + assertThrows(IllegalArgumentException.class, () -> { + forumController.newMessage(message, userId, forumId); + }); + verify(ChatRepository, never()).save(any(ForumChatModel.class)); + } + + @Test + @Tag("invalid") + void addMessageWithInvalidForumId() { + String message = "Test message"; + int userId = 1; + int forumId = -1; + assertThrows(IllegalArgumentException.class, () -> { + forumController.newMessage(message, userId, forumId); + }); + verify(ChatRepository, never()).save(any(ForumChatModel.class)); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerShowMessagesTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerShowMessagesTest.java new file mode 100644 index 0000000..7eec220 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerShowMessagesTest.java @@ -0,0 +1,194 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=showMessages_7de7018eb8 +ROOST_METHOD_SIG_HASH=showMessages_778e9dc544 + +Scenario 1: Retrieve All Messages Successfully + +Details: + TestName: retrieveAllMessages + Description: Verify that the showMessages method returns all forum chat messages stored in the repository. + +Execution: + Arrange: + - Mock the ChatRepository + - Populate the mock repository with a known set of ForumChatModel objects + + Act: + - Call the showMessages() method + + Assert: + - Verify that the returned Iterable contains all the messages from the mock repository + - Check that the size of the returned Iterable matches the number of messages in the mock repository + +Validation: + This test ensures that the showMessages method correctly retrieves all messages from the repository without any filtering or modification. It's crucial for verifying the basic functionality of displaying all forum messages to users. + +Scenario 2: Return Empty List When No Messages Exist + +Details: + TestName: returnEmptyListForNoMessages + Description: Confirm that the showMessages method returns an empty Iterable when there are no messages in the repository. + +Execution: + Arrange: + - Mock the ChatRepository + - Ensure the mock repository is empty + + Act: + - Call the showMessages() method + + Assert: + - Verify that the returned Iterable is empty + - Check that the size of the returned Iterable is zero + +Validation: + This test is important to verify the behavior of the method when the forum has no messages. It ensures that the application handles this edge case gracefully and doesn't throw an exception or return null. + +Scenario 3: Handle Large Number of Messages + +Details: + TestName: handleLargeNumberOfMessages + Description: Test the showMessages method's ability to handle and return a large number of messages efficiently. + +Execution: + Arrange: + - Mock the ChatRepository + - Populate the mock repository with a large number of ForumChatModel objects (e.g., 10,000 messages) + + Act: + - Call the showMessages() method and measure the execution time + + Assert: + - Verify that all messages are returned correctly + - Check that the method executes within an acceptable time frame (e.g., under 5 seconds) + +Validation: + This test is crucial for ensuring the performance and scalability of the showMessages method. It verifies that the method can handle a large volume of data without significant delays or memory issues, which is important for forums with high activity. + +Scenario 4: Consistency of Returned Data + +Details: + TestName: ensureDataConsistency + Description: Verify that the data returned by showMessages is consistent with the data in the repository. + +Execution: + Arrange: + - Mock the ChatRepository + - Add a set of ForumChatModel objects with known attributes to the mock repository + + Act: + - Call the showMessages() method + + Assert: + - Iterate through the returned Iterable + - For each ForumChatModel, verify that its attributes (message content, user ID, forum ID) match the corresponding object in the mock repository + +Validation: + This test ensures the integrity of the data returned by showMessages. It's important to verify that the method doesn't alter or misrepresent the data from the repository, maintaining the accuracy of the forum messages displayed to users. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.*; + +class ForumControllerShowMessagesTest { + + @Mock + private ForumChatRepository ChatRepository; + + private ForumController forumController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + forumController = new ForumController(); + forumController.ChatRepository = ChatRepository; + } + + @Test + @Tag("valid") + void retrieveAllMessages() { + List mockMessages = new ArrayList<>(); + mockMessages.add(new ForumChatModel("Message 1", 1, 1)); + mockMessages.add(new ForumChatModel("Message 2", 2, 1)); + when(ChatRepository.findAll()).thenReturn(mockMessages); + Iterable result = forumController.showMessages(); + assertNotNull(result); + List resultList = new ArrayList<>(); + result.forEach(resultList::add); + assertEquals(2, resultList.size()); + assertEquals("Message 1", resultList.get(0).getMessage()); + assertEquals("Message 2", resultList.get(1).getMessage()); + verify(ChatRepository, times(1)).findAll(); + } + + @Test + @Tag("valid") + void returnEmptyListForNoMessages() { + when(ChatRepository.findAll()).thenReturn(new ArrayList<>()); + Iterable result = forumController.showMessages(); + assertNotNull(result); + assertFalse(result.iterator().hasNext()); + verify(ChatRepository, times(1)).findAll(); + } + + @Test + @Tag("boundary") + void handleLargeNumberOfMessages() { + List mockMessages = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + mockMessages.add(new ForumChatModel("Message " + i, i % 100, i % 10)); + } + when(ChatRepository.findAll()).thenReturn(mockMessages); + long startTime = System.currentTimeMillis(); + Iterable result = forumController.showMessages(); + long endTime = System.currentTimeMillis(); + assertNotNull(result); + List resultList = new ArrayList<>(); + result.forEach(resultList::add); + assertEquals(10000, resultList.size()); + assertTrue((endTime - startTime) < 5000, "Method execution took longer than 5 seconds"); + verify(ChatRepository, times(1)).findAll(); + } + + @Test + @Tag("valid") + void ensureDataConsistency() { + List mockMessages = new ArrayList<>(); + mockMessages.add(new ForumChatModel("Message 1", 1, 1)); + mockMessages.add(new ForumChatModel("Message 2", 2, 1)); + mockMessages.add(new ForumChatModel("Message 3", 3, 2)); + when(ChatRepository.findAll()).thenReturn(mockMessages); + Iterable result = forumController.showMessages(); + assertNotNull(result); + List resultList = new ArrayList<>(); + result.forEach(resultList::add); + assertEquals(3, resultList.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(mockMessages.get(i).getMessage(), resultList.get(i).getMessage()); + assertEquals(mockMessages.get(i).getUserId(), resultList.get(i).getUserId()); + assertEquals(mockMessages.get(i).getForumId(), resultList.get(i).getForumId()); + } + verify(ChatRepository, times(1)).findAll(); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/LogControllerShowAllLogTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/LogControllerShowAllLogTest.java new file mode 100644 index 0000000..94a585e --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/LogControllerShowAllLogTest.java @@ -0,0 +1,166 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=showAllLog_66d6a0e563 +ROOST_METHOD_SIG_HASH=showAllLog_dafc374432 + +Scenario 1: Retrieve All Logs Successfully + +Details: + TestName: retrieveAllLogsSuccessfully + Description: This test verifies that the showAllLog method correctly retrieves all log entries when the log repository contains data. + +Execution: + Arrange: + - Create a mock LogRepository + - Populate the mock repository with sample LogModel objects + - Set up the LogController with the mock repository + Act: + - Call the showAllLog method + Assert: + - Verify that the returned Iterable is not null + - Verify that the returned Iterable contains all the sample log entries + +Validation: + This test ensures that the showAllLog method correctly interfaces with the LogRepository to retrieve all existing log entries. It validates that the method returns a non-null Iterable containing all the log entries present in the repository, which is crucial for the proper functioning of the log display feature in the application. + +Scenario 2: Retrieve Empty Log List + +Details: + TestName: retrieveEmptyLogList + Description: This test checks the behavior of the showAllLog method when the log repository is empty. + +Execution: + Arrange: + - Create a mock LogRepository + - Ensure the mock repository is empty + - Set up the LogController with the mock repository + Act: + - Call the showAllLog method + Assert: + - Verify that the returned Iterable is not null + - Verify that the returned Iterable is empty + +Validation: + This test validates that the showAllLog method handles the case of an empty log repository correctly. It ensures that the method returns a non-null but empty Iterable when there are no log entries, which is important for proper error handling and UI display in the absence of log data. + +Scenario 3: Handle Repository Exception + +Details: + TestName: handleRepositoryException + Description: This test verifies the behavior of the showAllLog method when the LogRepository throws an exception. + +Execution: + Arrange: + - Create a mock LogRepository + - Configure the mock to throw a RuntimeException when findAll() is called + - Set up the LogController with the mock repository + Act: + - Call the showAllLog method and catch any thrown exception + Assert: + - Verify that a RuntimeException is thrown + - Optionally, verify the exception message or type if specific exception handling is implemented + +Validation: + This test ensures that the showAllLog method properly handles exceptions that may occur during the retrieval of log entries from the repository. It validates the error handling capabilities of the method, which is crucial for maintaining the robustness and reliability of the logging system in the face of unexpected errors. + +Scenario 4: Verify Correct Repository Method Called + +Details: + TestName: verifyCorrectRepositoryMethodCalled + Description: This test ensures that the showAllLog method calls the correct method (findAll) on the LogRepository. + +Execution: + Arrange: + - Create a mock LogRepository + - Set up the LogController with the mock repository + Act: + - Call the showAllLog method + Assert: + - Verify that the findAll() method was called exactly once on the mock LogRepository + +Validation: + This test validates that the showAllLog method interacts correctly with the LogRepository by calling the appropriate method (findAll). It ensures that the controller is using the repository as intended, which is essential for maintaining the correct functionality and potential future modifications to the log retrieval process. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootTest +class LogControllerShowAllLogTest { + + private LogController logController; + + @Mock + private LogRepository logRepository; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + logController = new LogController(); + logController.Log = logRepository; + } + + @Test + @Tag("valid") + void retrieveAllLogsSuccessfully() { + LogModel log1 = new LogModel(); + LogModel log2 = new LogModel(); + when(logRepository.findAll()).thenReturn(Arrays.asList(log1, log2)); + Iterable result = logController.showAllLog(); + assertNotNull(result); + assertEquals(2, ((List) result).size()); + assertTrue(((List) result).contains(log1)); + assertTrue(((List) result).contains(log2)); + verify(logRepository, times(1)).findAll(); + } + + @Test + @Tag("valid") + void retrieveEmptyLogList() { + when(logRepository.findAll()).thenReturn(Collections.emptyList()); + Iterable result = logController.showAllLog(); + assertNotNull(result); + assertFalse(result.iterator().hasNext()); + verify(logRepository, times(1)).findAll(); + } + + @Test + @Tag("invalid") + void handleRepositoryException() { + when(logRepository.findAll()).thenThrow(new RuntimeException("Database error")); + assertThrows(RuntimeException.class, () -> logController.showAllLog()); + verify(logRepository, times(1)).findAll(); + } + + @Test + @Tag("integration") + void verifyCorrectRepositoryMethodCalled() { + logController.showAllLog(); + verify(logRepository, times(1)).findAll(); + verifyNoMoreInteractions(logRepository); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerCreateProductTest.java.invalid b/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerCreateProductTest.java.invalid new file mode 100644 index 0000000..0bf53ad --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerCreateProductTest.java.invalid @@ -0,0 +1,151 @@ +//This test file is marked invalid as it contains compilation errors. Change the extension to of this file to .java, to manually edit its contents + + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=createProduct_2b4ce50b8c +ROOST_METHOD_SIG_HASH=createProduct_7aa14a7887 + +Scenario 1: Successful Product Creation + +Details: + TestName: createProductSuccessfully + Description: Verify that a product is created successfully with valid input parameters. + +Execution: + Arrange: + - Mock ProductModelRepository and LogRepository + - Prepare valid input parameters: description, price, musicId, userId, listProduct + Act: + - Call createProduct method with valid parameters + Assert: + - Verify that ProductRepository.save() is called once with the correct ProductModel + - Verify that Log.save() is called once with the correct LogModel + - Check if the method returns "Produto Criado" + +Validation: + This test ensures that the createProduct method correctly creates a new product, saves it to the repository, logs the action, and returns the expected success message. It validates the core functionality of the product creation process. + +Scenario 2: Product Creation with Minimum Price + +Details: + TestName: createProductWithMinimumPrice + Description: Test product creation with the minimum allowed price (0.01). + +Execution: + Arrange: + - Mock ProductModelRepository and LogRepository + - Prepare input parameters with price set to 0.01 + Act: + - Call createProduct method + Assert: + - Verify that ProductRepository.save() is called with a ProductModel having price 0.01 + - Check if the method returns "Produto Criado" + +Validation: + This test verifies that the system can handle the creation of a product with the minimum possible price, ensuring that edge cases in pricing are handled correctly. + +Scenario 3: Product Creation with Maximum Price + +Details: + TestName: createProductWithMaximumPrice + Description: Test product creation with a very high price to check for any upper limits. + +Execution: + Arrange: + - Mock ProductModelRepository and LogRepository + - Prepare input parameters with a very high price (e.g., 999999999.99) + Act: + - Call createProduct method + Assert: + - Verify that ProductRepository.save() is called with a ProductModel having the high price + - Check if the method returns "Produto Criado" + +Validation: + This test ensures that the system can handle extremely high prices without any issues, validating that there are no unexpected upper limits on product pricing. + +Scenario 4: Product Creation with Empty Description + +Details: + TestName: createProductWithEmptyDescription + Description: Verify the behavior when creating a product with an empty description. + +Execution: + Arrange: + - Mock ProductModelRepository and LogRepository + - Prepare input parameters with an empty string for description + Act: + - Call createProduct method + Assert: + - Verify that ProductRepository.save() is called with a ProductModel having an empty description + - Check if the method returns "Produto Criado" + +Validation: + This test checks if the system allows the creation of products with empty descriptions, which might be important for certain types of products or could indicate a need for input validation. + +Scenario 5: Product Creation with Negative Music ID + +Details: + TestName: createProductWithNegativeMusicId + Description: Test the system's response to a negative musicId input. + +Execution: + Arrange: + - Mock ProductModelRepository and LogRepository + - Prepare input parameters with a negative value for musicId + Act: + - Call createProduct method + Assert: + - Observe if the method throws an exception or handles the negative musicId gracefully + - If no exception, verify that ProductRepository.save() is called with the negative musicId + +Validation: + This test explores how the system handles invalid input for musicId, which could reveal potential input validation issues or unexpected behavior with negative IDs. + +Scenario 6: Verify Logging Functionality + +Details: + TestName: verifyLoggingOnProductCreation + Description: Ensure that the logging functionality works correctly when creating a product. + +Execution: + Arrange: + - Mock ProductModelRepository and LogRepository + - Prepare valid input parameters + Act: + - Call createProduct method + Assert: + - Verify that Log.save() is called exactly once + - Check if the LogModel passed to Log.save() has the correct endpoint ("product/create/{userid}") and action ("Product") + - Ensure the timestamp in the LogModel is reasonably close to the current time + +Validation: + This test specifically focuses on the logging aspect of the product creation process, ensuring that each product creation is properly logged with the correct information for auditing and tracking purposes. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers;import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import com.medeiros.SPRINGProject.Models.ProductModel; +import com.medeiros.SPRINGProject.Models.ProductModelRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@Test +@Tag("integration") +void verifyLoggingOnProductCreation() { + String description = "Logging Test Product"; + double price = 20.99; + int musicId = 2; + int userId = 1; + String listProduct = "LoggingTestList"; + marketController.createProduct(description, price, musicId, userId, listProduct); + verify(logRepository, times(1)).save(argThat(log -> + log.getComando().equals("product/create/{userid}") && + log.getClasse().equals("Product") && + log.getData() != null + )); +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerDeleteProductTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerDeleteProductTest.java new file mode 100644 index 0000000..fd5c252 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerDeleteProductTest.java @@ -0,0 +1,165 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=deleteProduct_3207cdc0ca +ROOST_METHOD_SIG_HASH=deleteProduct_2e765309a5 + +Scenario 1: Successfully delete an existing product + +Details: + TestName: deleteExistingProduct + Description: Test the deletion of an existing product from the repository. + +Execution: + Arrange: + - Create a mock ProductModelRepository + - Add a sample product with ID 1 to the mock repository + Act: + - Call deleteProduct(1) + Assert: + - Verify that deleteById(1) was called on the mock repository + - Check that the method returns "Produto Deletado" + +Validation: + This test ensures that the deleteProduct method correctly calls the repository's deleteById method for an existing product ID and returns the expected confirmation message. It verifies the basic functionality of product deletion in the system. + +Scenario 2: Attempt to delete a non-existent product + +Details: + TestName: deleteNonExistentProduct + Description: Test the behavior when trying to delete a product that doesn't exist in the repository. + +Execution: + Arrange: + - Create a mock ProductModelRepository + - Configure the mock to throw EmptyResultDataAccessException when deleteById is called with ID 999 + Act: + - Call deleteProduct(999) + Assert: + - Verify that deleteById(999) was called on the mock repository + - Check that the method throws EmptyResultDataAccessException + +Validation: + This test verifies that the deleteProduct method handles the case of a non-existent product appropriately by allowing the exception to propagate. It ensures that the system behaves correctly when attempting to delete a product that is not in the database. + +Scenario 3: Delete product and log the action + +Details: + TestName: deleteProductAndLogAction + Description: Test that deleting a product also logs the action in the system. + +Execution: + Arrange: + - Create mock ProductModelRepository and LogRepository + - Add a sample product with ID 5 to the mock ProductModelRepository + Act: + - Call deleteProduct(5) + Assert: + - Verify that deleteById(5) was called on the mock ProductModelRepository + - Verify that save() was called on the mock LogRepository with a LogModel containing appropriate details + - Check that the method returns "Produto Deletado" + +Validation: + This test ensures that when a product is deleted, the action is not only performed in the product repository but also logged in the system. It verifies the integration between product deletion and action logging, which is important for maintaining an audit trail of system operations. + +Scenario 4: Handle database connection error during product deletion + +Details: + TestName: handleDatabaseErrorDuringDeletion + Description: Test the behavior when a database connection error occurs during product deletion. + +Execution: + Arrange: + - Create a mock ProductModelRepository + - Configure the mock to throw DataAccessException when deleteById is called + Act: + - Call deleteProduct(10) + Assert: + - Verify that deleteById(10) was called on the mock repository + - Check that the method throws DataAccessException + +Validation: + This test verifies that the deleteProduct method properly handles database connection errors by allowing the DataAccessException to propagate. It ensures that the system can gracefully handle unexpected database issues during the product deletion process. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import com.medeiros.SPRINGProject.Models.ProductModel; +import com.medeiros.SPRINGProject.Models.ProductModelRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.EmptyResultDataAccessException; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +class MarketControllerDeleteProductTest { + + @Mock + private ProductModelRepository productRepository; + + @Mock + private LogRepository logRepository; + + @InjectMocks + private MarketController marketController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void deleteExistingProduct() { + int productId = 1; + String result = marketController.deleteProduct(productId); + + verify(productRepository).deleteById(productId); + assertEquals("Produto Deletado", result); + } + + @Test + @Tag("invalid") + void deleteNonExistentProduct() { + int nonExistentId = 999; + doThrow(new EmptyResultDataAccessException(1)).when(productRepository).deleteById(nonExistentId); + assertThrows(EmptyResultDataAccessException.class, () -> marketController.deleteProduct(nonExistentId)); + verify(productRepository).deleteById(nonExistentId); + } + + @Test + @Tag("integration") + void deleteProductAndLogAction() { + int productId = 5; + String result = marketController.deleteProduct(productId); + verify(productRepository).deleteById(productId); + verify(logRepository).save(any(LogModel.class)); + assertEquals("Produto Deletado", result); + } + + @Test + @Tag("invalid") + void handleDatabaseErrorDuringDeletion() { + int productId = 10; + doThrow(new DataAccessException("Database connection error") { + }).when(productRepository).deleteById(productId); + assertThrows(DataAccessException.class, () -> marketController.deleteProduct(productId)); + verify(productRepository).deleteById(productId); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerShowAllProductsTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerShowAllProductsTest.java new file mode 100644 index 0000000..a41dfbc --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MarketControllerShowAllProductsTest.java @@ -0,0 +1,181 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=showAllProducts_e3f486dbbd +ROOST_METHOD_SIG_HASH=showAllProducts_f2f96749da + +Scenario 1: Retrieve All Products Successfully + +Details: + TestName: retrieveAllProductsSuccessfully + Description: Verify that the showAllProducts method returns all products from the repository. + +Execution: + Arrange: + - Mock the ProductRepository + - Prepare a list of sample ProductModel objects + - Set up the mock to return the sample list when findAll() is called + + Act: + - Call the showAllProducts() method + + Assert: + - Verify that the returned Iterable matches the sample list + +Validation: + This test ensures that the showAllProducts method correctly retrieves all products from the repository. It's crucial for verifying that the method returns the complete set of products without any filtering or modification. + +Scenario 2: Empty Product List + +Details: + TestName: emptyProductList + Description: Verify that the showAllProducts method returns an empty list when there are no products in the repository. + +Execution: + Arrange: + - Mock the ProductRepository + - Set up the mock to return an empty list when findAll() is called + + Act: + - Call the showAllProducts() method + + Assert: + - Verify that the returned Iterable is empty + +Validation: + This test case is important to ensure that the method behaves correctly when there are no products in the repository. It verifies that an empty list is returned rather than null or throwing an exception. + +Scenario 3: Large Number of Products + +Details: + TestName: largeNumberOfProducts + Description: Verify that the showAllProducts method can handle a large number of products without performance issues. + +Execution: + Arrange: + - Mock the ProductRepository + - Prepare a large list of sample ProductModel objects (e.g., 10,000 items) + - Set up the mock to return the large sample list when findAll() is called + + Act: + - Call the showAllProducts() method and measure the execution time + + Assert: + - Verify that the returned Iterable matches the large sample list + - Check that the execution time is within an acceptable range + +Validation: + This test ensures that the showAllProducts method can handle a large dataset efficiently. It's important for verifying the method's performance and scalability in real-world scenarios with extensive product catalogs. + +Scenario 4: Repository Throws Exception + +Details: + TestName: repositoryThrowsException + Description: Verify that the showAllProducts method handles exceptions thrown by the repository appropriately. + +Execution: + Arrange: + - Mock the ProductRepository + - Set up the mock to throw a RuntimeException when findAll() is called + + Act: + - Call the showAllProducts() method + + Assert: + - Verify that the method throws an appropriate exception or handles the error gracefully + +Validation: + This test case is crucial for ensuring robust error handling in the showAllProducts method. It verifies that the method doesn't crash the application when the underlying repository encounters issues, and instead manages the error appropriately. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.ProductModel; +import com.medeiros.SPRINGProject.Models.ProductModelRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@SpringBootTest +class MarketControllerShowAllProductsTest { + + @Mock + private ProductModelRepository productRepository; + + @InjectMocks + private MarketController marketController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void retrieveAllProductsSuccessfully() { + List sampleProducts = Arrays.asList(new ProductModel("Product 1", 10.0, 1, 1, "List1"), + new ProductModel("Product 2", 20.0, 2, 2, "List2")); + when(productRepository.findAll()).thenReturn(sampleProducts); + Iterable result = marketController.showAllProducts(); + assertIterableEquals(sampleProducts, result); + verify(productRepository, times(1)).findAll(); + } + + @Test + @Tag("valid") + void emptyProductList() { + when(productRepository.findAll()).thenReturn(Collections.emptyList()); + Iterable result = marketController.showAllProducts(); + assertFalse(result.iterator().hasNext()); + verify(productRepository, times(1)).findAll(); + } + + @Test + @Tag("valid") + void largeNumberOfProducts() { + List largeProductList = generateLargeProductList(10000); + when(productRepository.findAll()).thenReturn(largeProductList); + long startTime = System.currentTimeMillis(); + Iterable result = marketController.showAllProducts(); + long endTime = System.currentTimeMillis(); + assertIterableEquals(largeProductList, result); + assertTrue((endTime - startTime) < 1000, "Method execution took too long"); + verify(productRepository, times(1)).findAll(); + } + + @Test + @Tag("invalid") + void repositoryThrowsException() { + when(productRepository.findAll()).thenThrow(new RuntimeException("Database error")); + assertThrows(RuntimeException.class, () -> marketController.showAllProducts()); + verify(productRepository, times(1)).findAll(); + } + + private List generateLargeProductList(int size) { + List largeList = new java.util.ArrayList<>(size); + for (int i = 0; i < size; i++) { + largeList.add(new ProductModel("Product " + i, i * 10.0, i, i, "List" + i)); + } + return largeList; + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerCreateMusicTest.java.invalid b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerCreateMusicTest.java.invalid new file mode 100644 index 0000000..4efe264 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerCreateMusicTest.java.invalid @@ -0,0 +1,135 @@ +//This test file is marked invalid as it contains compilation errors. Change the extension to of this file to .java, to manually edit its contents + + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=createMusic_9c5dad48b0 +ROOST_METHOD_SIG_HASH=createMusic_4606fc0d94 + +Scenario 1: Successfully Create Music + +Details: + TestName: createMusicWithValidParameters + Description: Test the creation of music with valid parameters and verify the successful operation. + +Execution: + Arrange: + - Mock MusicRepository + - Prepare valid input parameters: MusicDescription, MusicName, Music, and Userid + Act: + - Call createMusic method with the prepared parameters + Assert: + - Verify that MusicRepo.save() is called once with the correct MusicModel + - Check if the method returns "Operação Feita" + +Validation: + This test ensures that the createMusic method correctly creates a new MusicModel object with the given parameters and saves it to the repository. The success message "Operação Feita" should be returned, indicating the operation was completed successfully. + +Scenario 2: Create Music with Empty Parameters + +Details: + TestName: createMusicWithEmptyParameters + Description: Test the creation of music with empty string parameters to verify handling of edge cases. + +Execution: + Arrange: + - Mock MusicRepository + - Prepare input parameters with empty strings for MusicDescription, MusicName, and Music + - Use a valid Userid + Act: + - Call createMusic method with the prepared parameters + Assert: + - Verify that MusicRepo.save() is called once with a MusicModel containing empty strings + - Check if the method returns "Operação Feita" + +Validation: + This test verifies that the createMusic method can handle empty string inputs without throwing exceptions. It's important to ensure that the system can process such inputs, even if they might not be ideal in a real-world scenario. + +Scenario 3: Create Music with Very Long Strings + +Details: + TestName: createMusicWithLongStrings + Description: Test the creation of music with extremely long string inputs to check for any potential limitations or issues. + +Execution: + Arrange: + - Mock MusicRepository + - Prepare input parameters with very long strings (e.g., 10000 characters) for MusicDescription, MusicName, and Music + - Use a valid Userid + Act: + - Call createMusic method with the prepared parameters + Assert: + - Verify that MusicRepo.save() is called once with a MusicModel containing the long strings + - Check if the method returns "Operação Feita" + +Validation: + This test ensures that the createMusic method can handle extremely long input strings without truncation or errors. It's crucial to verify that the system can process such inputs correctly, as they might occur in real-world scenarios. + +Scenario 4: Create Music with Negative User ID + +Details: + TestName: createMusicWithNegativeUserId + Description: Test the creation of music with a negative user ID to verify how the system handles invalid user IDs. + +Execution: + Arrange: + - Mock MusicRepository + - Prepare valid input parameters for MusicDescription, MusicName, and Music + - Use a negative integer for Userid + Act: + - Call createMusic method with the prepared parameters + Assert: + - Verify that MusicRepo.save() is called once with a MusicModel containing the negative Userid + - Check if the method returns "Operação Feita" + +Validation: + This test verifies how the system handles negative user IDs. While the method doesn't explicitly check for this, it's important to ensure that it doesn't cause unexpected behavior or exceptions. The test also highlights a potential area for improvement in input validation. + +Scenario 5: Verify MusicModel Creation + +Details: + TestName: verifyMusicModelCreation + Description: Test that the MusicModel is created correctly with the provided parameters. + +Execution: + Arrange: + - Mock MusicRepository + - Prepare input parameters: MusicDescription, MusicName, Music, and Userid + - Set up a capture for the MusicModel passed to MusicRepo.save() + Act: + - Call createMusic method with the prepared parameters + Assert: + - Verify that the captured MusicModel has all fields matching the input parameters + +Validation: + This test ensures that the MusicModel is created correctly with all the provided parameters. It's crucial to verify that no data is lost or altered during the creation process, maintaining data integrity. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers;import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import com.medeiros.SPRINGProject.Models.MusicModel; +import com.medeiros.SPRINGProject.Models.MusicRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@Test +@Tag("valid") +void verifyMusicModelCreation() { + String musicDescription = "Test Description"; + String musicName = "Test Music"; + String music = "Test Music Data"; + int userId = 1; + ArgumentCaptor musicModelCaptor = ArgumentCaptor.forClass(MusicModel.class); + musicController.createMusic(musicDescription, musicName, music, userId); + verify(MusicRepo).save(musicModelCaptor.capture()); + MusicModel capturedModel = musicModelCaptor.getValue(); + // Use the field name 'MusicId' instead of a getter method + assertEquals(userId, capturedModel.MusicId); + assertEquals(musicName, capturedModel.MusicName); + assertEquals(music, capturedModel.Music); + assertEquals(musicDescription, capturedModel.MusicDescription); +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerDeleteMusicTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerDeleteMusicTest.java new file mode 100644 index 0000000..0d1a4ca --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerDeleteMusicTest.java @@ -0,0 +1,137 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=deleteMusic_e3b3d353e4 +ROOST_METHOD_SIG_HASH=deleteMusic_3c6d20ad7a + +Scenario 1: Successfully delete an existing music entry + +Details: + TestName: deleteMusicSuccessfully + Description: Verify that the deleteMusic method successfully removes an existing music entry from the repository and returns the expected confirmation message. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up an existing music entry with a known ID (e.g., 1) + Act: + - Call deleteMusic(1) + Assert: + - Verify that MusicRepo.deleteById(1) was called + - Check that the method returns "Deletado" + +Validation: + This test ensures that the deleteMusic method correctly interacts with the MusicRepository to remove the specified entry. It also validates that the method returns the expected confirmation message, indicating successful deletion to the user. + +Scenario 2: Attempt to delete a non-existent music entry + +Details: + TestName: deleteMusicNonExistent + Description: Test the behavior of deleteMusic when attempting to delete a music entry that doesn't exist in the repository. + +Execution: + Arrange: + - Create a mock MusicRepository + - Configure the mock to throw an exception when deleteById is called with a non-existent ID (e.g., 999) + Act: + - Call deleteMusic(999) + Assert: + - Verify that MusicRepo.deleteById(999) was called + - Check if the method handles the exception gracefully (if applicable) + - Ensure the method still returns "Deletado" despite the non-existent entry + +Validation: + This test verifies how the deleteMusic method handles attempts to delete non-existent entries. It's important to ensure that the method doesn't crash and still provides a consistent response, even when the requested music entry is not found in the repository. + +Scenario 3: Delete music with boundary value ID + +Details: + TestName: deleteMusicWithBoundaryId + Description: Test the deleteMusic method with boundary value IDs to ensure it handles edge cases correctly. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up test cases for boundary values (e.g., Integer.MAX_VALUE, Integer.MIN_VALUE) + Act: + - Call deleteMusic(Integer.MAX_VALUE) + - Call deleteMusic(Integer.MIN_VALUE) + Assert: + - Verify that MusicRepo.deleteById() was called with the correct boundary values + - Check that the method returns "Deletado" for both cases + +Validation: + This test ensures that the deleteMusic method can handle extreme ID values without errors. It's crucial to verify that the method works correctly with the full range of possible integer values, preventing potential overflow or underflow issues. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.MusicModel; +import com.medeiros.SPRINGProject.Models.MusicRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.dao.EmptyResultDataAccessException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +class MusicControllerDeleteMusicTest { + + @Mock + private MusicRepository musicRepo; + + @InjectMocks + private MusicController musicController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void deleteMusicSuccessfully() { + int musicId = 1; + doNothing().when(musicRepo).deleteById(musicId); + String result = musicController.deleteMusic(musicId); + verify(musicRepo, times(1)).deleteById(musicId); + assertEquals("Deletado", result); + } + + @Test + @Tag("invalid") + void deleteMusicNonExistent() { + int nonExistentId = 999; + doThrow(new EmptyResultDataAccessException(1)).when(musicRepo).deleteById(nonExistentId); + String result = musicController.deleteMusic(nonExistentId); + verify(musicRepo, times(1)).deleteById(nonExistentId); + assertEquals("Deletado", result); + } + + @Test + @Tag("boundary") + void deleteMusicWithBoundaryId() { + doNothing().when(musicRepo).deleteById(anyInt()); + String resultMax = musicController.deleteMusic(Integer.MAX_VALUE); + String resultMin = musicController.deleteMusic(Integer.MIN_VALUE); + verify(musicRepo, times(1)).deleteById(Integer.MAX_VALUE); + verify(musicRepo, times(1)).deleteById(Integer.MIN_VALUE); + assertEquals("Deletado", resultMax); + assertEquals("Deletado", resultMin); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerFindMusicByTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerFindMusicByTest.java new file mode 100644 index 0000000..64c2586 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerFindMusicByTest.java @@ -0,0 +1,186 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=findMusicBy_5035b89150 +ROOST_METHOD_SIG_HASH=findMusicBy_179b3d7d86 + +Scenario 1: Successful retrieval of an existing music entry + +Details: + TestName: findExistingMusic + Description: Verify that the method correctly retrieves a MusicModel object when given a valid ID. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up the mock to return a valid MusicModel object for a specific ID (e.g., 1) + Act: + - Call findMusicBy(1) on the MusicController instance + Assert: + - Verify that the returned object is not null + - Verify that the returned object is of type MusicModel + - Verify that the returned object has the expected ID + +Validation: + This test ensures that the findMusicBy method correctly interacts with the MusicRepository to retrieve an existing music entry. It validates that the method returns the expected MusicModel object for a given valid ID, which is crucial for the proper functioning of music lookup operations in the application. + +Scenario 2: Attempt to retrieve a non-existent music entry + +Details: + TestName: findNonExistentMusic + Description: Verify that the method handles the case when no music entry exists for the given ID. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up the mock to return null for a non-existent ID (e.g., 999) + Act: + - Call findMusicBy(999) on the MusicController instance + Assert: + - Verify that the returned object is null + +Validation: + This test ensures that the findMusicBy method correctly handles cases where no music entry exists for the given ID. It validates that the method returns null in such scenarios, which is important for proper error handling and preventing null pointer exceptions in the calling code. + +Scenario 3: Handling of invalid ID input + +Details: + TestName: findMusicWithInvalidId + Description: Verify that the method handles invalid ID inputs gracefully. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up the mock to throw an IllegalArgumentException for an invalid ID (e.g., -1) + Act: + - Call findMusicBy(-1) on the MusicController instance + Assert: + - Verify that an IllegalArgumentException is thrown + +Validation: + This test ensures that the findMusicBy method properly handles invalid ID inputs, such as negative numbers. It validates that the method throws an appropriate exception, which is crucial for maintaining data integrity and providing meaningful error feedback to the calling code or end-users. + +Scenario 4: Performance under high load + +Details: + TestName: findMusicUnderHighLoad + Description: Verify that the method performs efficiently when called multiple times in quick succession. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up the mock to return valid MusicModel objects for a range of IDs (e.g., 1 to 1000) + Act: + - Call findMusicBy() 1000 times with different IDs in a loop + Assert: + - Verify that all calls complete within an acceptable time frame (e.g., under 5 seconds total) + - Verify that all returned objects are valid MusicModel instances + +Validation: + This test ensures that the findMusicBy method can handle multiple requests efficiently, which is important for the application's performance under high load. It validates that the method can quickly retrieve music entries without significant delays, even when called repeatedly with different IDs. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.MusicModel; +import com.medeiros.SPRINGProject.Models.MusicRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.boot.test.context.SpringBootTest; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@ExtendWith(MockitoExtension.class) +@SpringBootTest +class MusicControllerFindMusicByTest { + + @Mock + private MusicRepository MusicRepo; + + @InjectMocks + private MusicController musicController; + + @BeforeEach + void setUp() { + // Common setup if needed + } + + @Test + @Tag("valid") + void findExistingMusic() { + // Arrange + int id = 1; + MusicModel expectedMusic = new MusicModel(id, "Test Music", "Test Artist", "Test Description"); + when(MusicRepo.findById(id)).thenReturn(expectedMusic); + // Act + MusicModel result = musicController.findMusicBy(id); + // Assert + assertNotNull(result); + assertEquals(MusicModel.class, result.getClass()); + assertEquals(id, result.getId()); + verify(MusicRepo, times(1)).findById(id); + } + + @Test + @Tag("invalid") + void findNonExistentMusic() { + // Arrange + int id = 999; + when(MusicRepo.findById(id)).thenReturn(null); + // Act + MusicModel result = musicController.findMusicBy(id); + // Assert + assertNull(result); + verify(MusicRepo, times(1)).findById(id); + } + + @Test + @Tag("boundary") + void findMusicWithInvalidId() { + // Arrange + int id = -1; + when(MusicRepo.findById(id)).thenThrow(new IllegalArgumentException("Invalid ID")); + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> musicController.findMusicBy(id)); + verify(MusicRepo, times(1)).findById(id); + } + + @Test + @Tag("integration") + void findMusicUnderHighLoad() { + // Arrange + int numCalls = 1000; + long startTime = System.currentTimeMillis(); + // Act + for (int i = 1; i <= numCalls; i++) { + when(MusicRepo.findById(i)).thenReturn(new MusicModel(i, "Music " + i, "Artist " + i, "Description " + i)); + MusicModel result = musicController.findMusicBy(i); + // Assert for each call + assertNotNull(result); + assertEquals(MusicModel.class, result.getClass()); + assertEquals(i, result.getId()); + } + // Assert total execution time + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + assertTrue(duration < 5000, "High load test exceeded 5 seconds"); + // Verify total number of calls + verify(MusicRepo, times(numCalls)).findById(anyInt()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerUpdateMusicByIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerUpdateMusicByIdTest.java new file mode 100644 index 0000000..ef6fee2 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/MusicControllerUpdateMusicByIdTest.java @@ -0,0 +1,214 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=updateMusicById_aa137517f5 +ROOST_METHOD_SIG_HASH=updateMusicById_857ee29aaf + +Scenario 1: Successfully update music details + +Details: + TestName: updateExistingMusicWithValidData + Description: Verify that the method successfully updates an existing music entry with valid data and returns the expected success message. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up a MusicModel with initial data + - Configure the mock repository to return the MusicModel when findById is called + + Act: + - Call updateMusicById with valid ID and new music details + + Assert: + - Verify that the returned string is "Música Alterada!" + - Check that the save method of MusicRepository was called once + - Confirm that the MusicModel's fields were updated with the new values + +Validation: + This test ensures that the method correctly updates an existing music entry in the database when provided with valid data. It verifies that the success message is returned and that the repository's save method is called to persist the changes. + +Scenario 2: Attempt to update non-existent music + +Details: + TestName: updateNonExistentMusic + Description: Verify that the method handles the scenario where the specified music ID does not exist in the database. + +Execution: + Arrange: + - Create a mock MusicRepository + - Configure the mock repository to return null when findById is called + + Act: + - Call updateMusicById with a non-existent ID and some music details + + Assert: + - Verify that a NullPointerException is thrown + - Check that the save method of MusicRepository was not called + +Validation: + This test ensures that the method properly handles cases where the specified music ID does not exist in the database. It verifies that an appropriate exception is thrown and that no update operation is attempted on non-existent data. + +Scenario 3: Update music with empty string values + +Details: + TestName: updateMusicWithEmptyStrings + Description: Verify that the method handles updates with empty string values for music name, description, and music content. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up a MusicModel with initial non-empty data + - Configure the mock repository to return the MusicModel when findById is called + + Act: + - Call updateMusicById with a valid ID and empty strings for all parameters + + Assert: + - Verify that the returned string is "Música Alterada!" + - Check that the save method of MusicRepository was called once + - Confirm that the MusicModel's fields were updated with empty strings + +Validation: + This test ensures that the method allows updating music details with empty strings, which might be a valid use case in some scenarios. It verifies that the update operation is performed and the success message is returned even with empty input. + +Scenario 4: Update music with very long string values + +Details: + TestName: updateMusicWithLongStrings + Description: Verify that the method can handle updates with very long string values for music name, description, and music content. + +Execution: + Arrange: + - Create a mock MusicRepository + - Set up a MusicModel with initial data + - Configure the mock repository to return the MusicModel when findById is called + - Prepare very long strings (e.g., 10000 characters) for each parameter + + Act: + - Call updateMusicById with a valid ID and the long string values + + Assert: + - Verify that the returned string is "Música Alterada!" + - Check that the save method of MusicRepository was called once + - Confirm that the MusicModel's fields were updated with the long string values + +Validation: + This test ensures that the method can handle and store very long string inputs without truncation or errors. It verifies the system's ability to process and save large amounts of text data, which might be necessary for detailed music descriptions or lyrics. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.MusicModel; +import com.medeiros.SPRINGProject.Models.MusicRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +class MusicControllerUpdateMusicByIdTest { + + @Mock + private MusicRepository MusicRepo; + + @InjectMocks + private MusicController musicController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void updateExistingMusicWithValidData() { + // Arrange + int id = 1; + String musicName = "New Song"; + String musicDescription = "Updated description"; + String music = "Updated music content"; + MusicModel existingMusic = new MusicModel(); + existingMusic.setId(id); + existingMusic.setMusicName("Old Song"); + existingMusic.setMusicDescription("Old description"); + existingMusic.setMusic("Old music content"); + when(MusicRepo.findById(id)).thenReturn(existingMusic); + // Act + String result = musicController.updateMusicById(id, musicName, musicDescription, music); + // Assert + assertEquals("Música Alterada!", result); + verify(MusicRepo, times(1)).save(existingMusic); + assertEquals(musicName, existingMusic.getMusicName()); + assertEquals(musicDescription, existingMusic.getMusicDescription()); + assertEquals(music, existingMusic.getMusic()); + } + + @Test + @Tag("invalid") + void updateNonExistentMusic() { + // Arrange + int id = 999; + when(MusicRepo.findById(id)).thenReturn(null); + // Act & Assert + assertThrows(NullPointerException.class, + () -> musicController.updateMusicById(id, "New Song", "Description", "Music")); + verify(MusicRepo, never()).save(any()); + } + + @Test + @Tag("boundary") + void updateMusicWithEmptyStrings() { + // Arrange + int id = 1; + MusicModel existingMusic = new MusicModel(); + existingMusic.setId(id); + existingMusic.setMusicName("Old Song"); + existingMusic.setMusicDescription("Old description"); + existingMusic.setMusic("Old music content"); + when(MusicRepo.findById(id)).thenReturn(existingMusic); + // Act + String result = musicController.updateMusicById(id, "", "", ""); + // Assert + assertEquals("Música Alterada!", result); + verify(MusicRepo, times(1)).save(existingMusic); + assertEquals("", existingMusic.getMusicName()); + assertEquals("", existingMusic.getMusicDescription()); + assertEquals("", existingMusic.getMusic()); + } + + @Test + @Tag("boundary") + void updateMusicWithLongStrings() { + // Arrange + int id = 1; + String longString = "a".repeat(10000); + MusicModel existingMusic = new MusicModel(); + existingMusic.setId(id); + existingMusic.setMusicName("Old Song"); + existingMusic.setMusicDescription("Old description"); + existingMusic.setMusic("Old music content"); + when(MusicRepo.findById(id)).thenReturn(existingMusic); + // Act + String result = musicController.updateMusicById(id, longString, longString, longString); + // Assert + assertEquals("Música Alterada!", result); + verify(MusicRepo, times(1)).save(existingMusic); + assertEquals(longString, existingMusic.getMusicName()); + assertEquals(longString, existingMusic.getMusicDescription()); + assertEquals(longString, existingMusic.getMusic()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/PagesControllerMinhaPaginaTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/PagesControllerMinhaPaginaTest.java new file mode 100644 index 0000000..c3638e8 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/PagesControllerMinhaPaginaTest.java @@ -0,0 +1,167 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=minhaPagina_faf3e427f2 +ROOST_METHOD_SIG_HASH=minhaPagina_b5557d79c5 + +Scenario 1: Verify correct ModelAndView creation and attribute setting + +Details: + TestName: minhaPaginaReturnsCorrectModelAndView + Description: This test verifies that the minhaPagina method creates a ModelAndView object with the correct view name and attributes. + +Execution: + Arrange: No specific arrangement needed as the method doesn't depend on any external data. + Act: Call the minhaPagina() method and store the returned ModelAndView object. + Assert: + - Check that the returned object is not null. + - Verify that the view name is "minhaPagina". + - Confirm that the "titulo" attribute is set to "Minha Página". + - Ensure that the "mensagem" attribute is set to "Bem-vindo à minha página!". + +Validation: + This test ensures that the minhaPagina method correctly creates a ModelAndView object with the expected view name and attributes. It's crucial for verifying that the correct data is being passed to the view, which affects how the page will be rendered to the user. + +Scenario 2: Check for null attributes in ModelAndView + +Details: + TestName: minhaPaginaAttributesNotNull + Description: This test checks that none of the attributes added to the ModelAndView are null. + +Execution: + Arrange: No specific arrangement needed. + Act: Call the minhaPagina() method and store the returned ModelAndView object. + Assert: + - Verify that the "titulo" attribute is not null. + - Verify that the "mensagem" attribute is not null. + +Validation: + This test ensures that the method doesn't accidentally set any of the crucial attributes to null, which could lead to errors when rendering the view or unexpected behavior in the UI. + +Scenario 3: Verify ModelAndView attribute types + +Details: + TestName: minhaPaginaAttributeTypes + Description: This test verifies that the attributes added to the ModelAndView are of the correct data type. + +Execution: + Arrange: No specific arrangement needed. + Act: Call the minhaPagina() method and store the returned ModelAndView object. + Assert: + - Check that the "titulo" attribute is of type String. + - Check that the "mensagem" attribute is of type String. + +Validation: + This test ensures that the attributes are set with the correct data types. Using incorrect types could lead to type casting errors or unexpected behavior when the view tries to use these attributes. + +Scenario 4: Check for unexpected attributes + +Details: + TestName: minhaPaginaNoUnexpectedAttributes + Description: This test verifies that no unexpected attributes are added to the ModelAndView. + +Execution: + Arrange: No specific arrangement needed. + Act: Call the minhaPagina() method and store the returned ModelAndView object. + Assert: + - Verify that the ModelAndView contains exactly two attributes. + - Confirm that these attributes are named "titulo" and "mensagem". + +Validation: + This test ensures that the method doesn't accidentally add any unexpected attributes to the ModelAndView. Extra attributes could indicate a bug or could lead to confusion or errors in the view. + +Scenario 5: Verify method consistency across multiple calls + +Details: + TestName: minhaPaginaConsistentResults + Description: This test checks if multiple calls to the minhaPagina method produce consistent results. + +Execution: + Arrange: No specific arrangement needed. + Act: + - Call the minhaPagina() method twice and store the returned ModelAndView objects. + Assert: + - Verify that both calls return non-null ModelAndView objects. + - Check that the view names are identical for both calls. + - Confirm that the "titulo" and "mensagem" attributes are identical for both calls. + +Validation: + This test ensures that the minhaPagina method behaves consistently across multiple invocations. Inconsistent results could indicate a problem with the method's implementation or unexpected side effects. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.LogModel; +import com.medeiros.SPRINGProject.Models.LogRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.springframework.web.servlet.ModelAndView; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +class PagesControllerMinhaPaginaTest { + + private PagesController pagesController; + + @BeforeEach + void setUp() { + pagesController = new PagesController(); + } + + @Test + @Tag("valid") + void minhaPaginaReturnsCorrectModelAndView() { + ModelAndView modelAndView = pagesController.minhaPagina(); + assertNotNull(modelAndView); + assertEquals("minhaPagina", modelAndView.getViewName()); + assertEquals("Minha Página", modelAndView.getModel().get("titulo")); + assertEquals("Bem-vindo à minha página!", modelAndView.getModel().get("mensagem")); + } + + @Test + @Tag("valid") + void minhaPaginaAttributesNotNull() { + ModelAndView modelAndView = pagesController.minhaPagina(); + assertNotNull(modelAndView.getModel().get("titulo")); + assertNotNull(modelAndView.getModel().get("mensagem")); + } + + @Test + @Tag("valid") + void minhaPaginaAttributeTypes() { + ModelAndView modelAndView = pagesController.minhaPagina(); + assertTrue(modelAndView.getModel().get("titulo") instanceof String); + assertTrue(modelAndView.getModel().get("mensagem") instanceof String); + } + + @Test + @Tag("valid") + void minhaPaginaNoUnexpectedAttributes() { + ModelAndView modelAndView = pagesController.minhaPagina(); + assertEquals(2, modelAndView.getModel().size()); + assertTrue(modelAndView.getModel().containsKey("titulo")); + assertTrue(modelAndView.getModel().containsKey("mensagem")); + } + + @Test + @Tag("valid") + void minhaPaginaConsistentResults() { + ModelAndView modelAndView1 = pagesController.minhaPagina(); + ModelAndView modelAndView2 = pagesController.minhaPagina(); + assertNotNull(modelAndView1); + assertNotNull(modelAndView2); + assertEquals(modelAndView1.getViewName(), modelAndView2.getViewName()); + assertEquals(modelAndView1.getModel().get("titulo"), modelAndView2.getModel().get("titulo")); + assertEquals(modelAndView1.getModel().get("mensagem"), modelAndView2.getModel().get("mensagem")); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerDeleteUserByIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerDeleteUserByIdTest.java new file mode 100644 index 0000000..5f705f6 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerDeleteUserByIdTest.java @@ -0,0 +1,188 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=deleteUserById_d65ace15d7 +ROOST_METHOD_SIG_HASH=deleteUserById_91ecd15d81 + +Scenario 1: Successfully Delete a User Account + +Details: + TestName: deleteExistingUser + Description: This test verifies that the method successfully deletes an existing user account when provided with a valid user ID. + +Execution: + Arrange: + - Create a mock UserAccRepository + - Set up a test user with a known ID (e.g., "123") + - Configure the mock repository to return successfully when deleteById is called + + Act: + - Call deleteUserById("123") + + Assert: + - Verify that UserAccRepo.deleteById was called with the integer value 123 + - Check that the method returns "Conta Deletada" + +Validation: + This test ensures that the method correctly parses the input string ID to an integer, calls the repository's deleteById method with the correct ID, and returns the expected success message. It validates the basic happy path functionality of the user deletion process. + +Scenario 2: Attempt to Delete a User with Invalid ID Format + +Details: + TestName: deleteUserWithInvalidIdFormat + Description: This test checks the method's behavior when provided with an ID that cannot be parsed into an integer. + +Execution: + Arrange: + - Create a mock UserAccRepository + + Act: + - Call deleteUserById("abc") + + Assert: + - Verify that a NumberFormatException is thrown + +Validation: + This test ensures that the method properly handles invalid input by throwing a NumberFormatException when the ID cannot be parsed into an integer. It's crucial for robust error handling and preventing unexpected behavior with malformed inputs. + +Scenario 3: Delete Non-Existent User + +Details: + TestName: deleteNonExistentUser + Description: This test verifies the method's behavior when attempting to delete a user that doesn't exist in the database. + +Execution: + Arrange: + - Create a mock UserAccRepository + - Configure the mock to throw an EmptyResultDataAccessException when deleteById is called with a non-existent ID + + Act: + - Call deleteUserById("999") + + Assert: + - Verify that an EmptyResultDataAccessException is thrown + +Validation: + This test ensures that the method correctly handles attempts to delete non-existent users. It's important to verify that the system behaves predictably when dealing with data that doesn't exist, potentially allowing for appropriate error handling or user feedback in the calling code. + +Scenario 4: Delete User with Null ID + +Details: + TestName: deleteUserWithNullId + Description: This test checks the method's response when called with a null ID parameter. + +Execution: + Arrange: + - Create a mock UserAccRepository + + Act: + - Call deleteUserById(null) + + Assert: + - Verify that a NullPointerException is thrown + +Validation: + This test ensures that the method properly handles null input by throwing a NullPointerException. It's important to validate that the method fails fast and predictably when given null input, rather than causing issues further down in the execution process. + +Scenario 5: Verify No Side Effects on Other Users + +Details: + TestName: verifyNoSideEffectsOnOtherUsers + Description: This test ensures that deleting one user does not affect other users in the system. + +Execution: + Arrange: + - Create a mock UserAccRepository + - Set up multiple test users with known IDs (e.g., "123", "456") + - Configure the mock repository to return successfully when deleteById is called for "123" + + Act: + - Call deleteUserById("123") + + Assert: + - Verify that UserAccRepo.deleteById was called only once with the integer value 123 + - Verify that no operations were performed on the user with ID "456" + +Validation: + This test ensures that the deletion process is specific to the given user ID and does not inadvertently affect other users in the system. It's crucial for maintaining data integrity and preventing unintended modifications to other user accounts. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.springframework.dao.EmptyResultDataAccessException; +import org.junit.jupiter.api.*; + +class UserAccountControllerDeleteUserByIdTest { + + @Mock + private UserAccRepository UserAccRepo; + + @InjectMocks + private UserAccountController userAccountController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void deleteExistingUser() { + String userId = "123"; + doNothing().when(UserAccRepo).deleteById(123); + String result = userAccountController.deleteUserById(userId); + verify(UserAccRepo, times(1)).deleteById(123); + assertEquals("Conta Deletada", result); + } + + @Test + @Tag("invalid") + void deleteUserWithInvalidIdFormat() { + String invalidId = "abc"; + assertThrows(NumberFormatException.class, () -> userAccountController.deleteUserById(invalidId)); + } + + @Test + @Tag("invalid") + void deleteNonExistentUser() { + String nonExistentId = "999"; + doThrow(new EmptyResultDataAccessException(1)).when(UserAccRepo).deleteById(999); + assertThrows(EmptyResultDataAccessException.class, () -> userAccountController.deleteUserById(nonExistentId)); + } + + @Test + @Tag("invalid") + void deleteUserWithNullId() { + assertThrows(NullPointerException.class, () -> userAccountController.deleteUserById(null)); + } + + @Test + @Tag("valid") + void verifyNoSideEffectsOnOtherUsers() { + String userId = "123"; + doNothing().when(UserAccRepo).deleteById(123); + userAccountController.deleteUserById(userId); + verify(UserAccRepo, times(1)).deleteById(123); + verify(UserAccRepo, never()).deleteById(456); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerFindUserByIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerFindUserByIdTest.java new file mode 100644 index 0000000..c59e342 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerFindUserByIdTest.java @@ -0,0 +1,187 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=findUserById_fca20bfdc9 +ROOST_METHOD_SIG_HASH=findUserById_46f9fcf424 + +Scenario 1: Successfully Find User by Valid ID + +Details: + TestName: findUserByValidId + Description: Test if the method correctly retrieves a user when given a valid ID. + +Execution: + Arrange: + - Mock UserAccRepository + - Set up a test User_Credentials object with a known ID (e.g., 1) + - Configure mock to return the test object when findById is called with 1 + + Act: + - Call findUserById with the string "1" + + Assert: + - Verify that the returned User_Credentials object matches the test object + +Validation: + This test ensures that the method can correctly parse a string ID, call the repository method, and return the expected User_Credentials object. It validates the happy path scenario where a user exists for the given ID. + +Scenario 2: Handle Non-Existent User ID + +Details: + TestName: findUserByNonExistentId + Description: Test the behavior when searching for a user with an ID that doesn't exist in the database. + +Execution: + Arrange: + - Mock UserAccRepository + - Configure mock to return null when findById is called with any integer + + Act: + - Call findUserById with a string ID that doesn't exist, e.g., "999" + + Assert: + - Verify that the method returns null + +Validation: + This test verifies that the method handles the case of a non-existent user gracefully by returning null, which is the expected behavior when the repository doesn't find a matching user. + +Scenario 3: Handle Invalid ID Format + +Details: + TestName: findUserByInvalidIdFormat + Description: Test the method's behavior when provided with an ID that cannot be parsed to an integer. + +Execution: + Arrange: + - No specific arrangement needed + + Act: + - Call findUserById with an invalid ID string, e.g., "abc" + + Assert: + - Verify that a NumberFormatException is thrown + +Validation: + This test ensures that the method throws a NumberFormatException when it cannot parse the input string to an integer. It's important to verify that the method fails predictably with invalid input. + +Scenario 4: Handle Null ID Input + +Details: + TestName: findUserByNullId + Description: Test the method's response when provided with a null ID. + +Execution: + Arrange: + - No specific arrangement needed + + Act: + - Call findUserById with null + + Assert: + - Verify that a NullPointerException is thrown + +Validation: + This test checks the method's behavior when given a null input. It's crucial to ensure that the method handles this edge case appropriately by throwing a NullPointerException, alerting the caller to an invalid input. + +Scenario 5: Handle Empty String ID + +Details: + TestName: findUserByEmptyStringId + Description: Test the method's behavior when provided with an empty string as ID. + +Execution: + Arrange: + - No specific arrangement needed + + Act: + - Call findUserById with an empty string "" + + Assert: + - Verify that a NumberFormatException is thrown + +Validation: + This test ensures that the method throws a NumberFormatException when trying to parse an empty string. It's important to verify that the method handles this edge case correctly and doesn't result in unexpected behavior. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.Optional; + +class UserAccountControllerFindUserByIdTest { + + @Mock + private UserAccRepository UserAccRepo; + + @InjectMocks + private UserAccountController userAccountController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void findUserByValidId() { + User_Credentials testUser = new User_Credentials(); + testUser.setId(1); + when(UserAccRepo.findById(1)).thenReturn(testUser); + User_Credentials result = userAccountController.findUserById("1"); + assertNotNull(result); + assertEquals(1, result.getId()); + verify(UserAccRepo).findById(1); + } + + @Test + @Tag("invalid") + void findUserByNonExistentId() { + when(UserAccRepo.findById(anyInt())).thenReturn(null); + User_Credentials result = userAccountController.findUserById("999"); + assertNull(result); + verify(UserAccRepo).findById(999); + } + + @Test + @Tag("invalid") + void findUserByInvalidIdFormat() { + assertThrows(NumberFormatException.class, () -> { + userAccountController.findUserById("abc"); + }); + } + + @Test + @Tag("invalid") + void findUserByNullId() { + assertThrows(NullPointerException.class, () -> { + userAccountController.findUserById(null); + }); + } + + @Test + @Tag("boundary") + void findUserByEmptyStringId() { + assertThrows(NumberFormatException.class, () -> { + userAccountController.findUserById(""); + }); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateInfoUserByTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateInfoUserByTest.java new file mode 100644 index 0000000..28d55fd --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateInfoUserByTest.java @@ -0,0 +1,228 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=updateInfoUserBy_b88001e4be +ROOST_METHOD_SIG_HASH=updateInfoUserBy_642c0765ab + +Scenario 1: Successful Update of User Information + +Details: + TestName: successfulUpdateOfUserInfo + Description: This test verifies that the method correctly updates user information when valid parameters are provided. + +Execution: + Arrange: + - Create a mock UserInfoRepo + - Set up expected input parameters (userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings) + Act: + - Call updateInfoUserBy method with the arranged parameters + Assert: + - Verify that UserInfoRepo.save() was called once with the correct User_Info object + - Check that the method returns "ATUALIZADO" + +Validation: + This test ensures that the method correctly creates a new User_Info object with the provided parameters and saves it to the repository. The success message "ATUALIZADO" should be returned, indicating that the update was successful. + +Scenario 2: Update with Null Values + +Details: + TestName: updateWithNullValues + Description: This test checks how the method handles null values for optional fields. + +Execution: + Arrange: + - Create a mock UserInfoRepo + - Set up input parameters with null values for optional fields (e.g., photoURL, instaURL, twitterURL) + Act: + - Call updateInfoUserBy method with the arranged parameters + Assert: + - Verify that UserInfoRepo.save() was called once with a User_Info object containing null values for the optional fields + - Check that the method returns "ATUALIZADO" + +Validation: + This test verifies that the method can handle null values for optional fields without throwing exceptions. It ensures that the update process continues even when some information is not provided. + +Scenario 3: Update with Empty Strings + +Details: + TestName: updateWithEmptyStrings + Description: This test examines how the method handles empty strings for text fields. + +Execution: + Arrange: + - Create a mock UserInfoRepo + - Set up input parameters with empty strings for text fields (e.g., favoritesMusics, favoritesThings) + Act: + - Call updateInfoUserBy method with the arranged parameters + Assert: + - Verify that UserInfoRepo.save() was called once with a User_Info object containing empty strings for the specified fields + - Check that the method returns "ATUALIZADO" + +Validation: + This test ensures that the method can process empty strings without issues, allowing users to clear previously set information if desired. + +Scenario 4: Update with Invalid User ID + +Details: + TestName: updateWithInvalidUserId + Description: This test checks the behavior of the method when an invalid user ID is provided. + +Execution: + Arrange: + - Create a mock UserInfoRepo that throws an exception when save() is called with an invalid user ID + - Set up input parameters with an invalid userId + Act: + - Call updateInfoUserBy method with the invalid userId + Assert: + - Verify that an appropriate exception is thrown (e.g., IllegalArgumentException) + - Check that UserInfoRepo.save() is not successfully completed + +Validation: + This test verifies that the method handles invalid user IDs appropriately, either by throwing an exception or returning an error message, preventing updates to non-existent user records. + +Scenario 5: Update with Very Long Input Strings + +Details: + TestName: updateWithVeryLongInputStrings + Description: This test examines how the method handles extremely long input strings for text fields. + +Execution: + Arrange: + - Create a mock UserInfoRepo + - Set up input parameters with very long strings (e.g., 1000 characters) for text fields like favoritesMusics and favoritesThings + Act: + - Call updateInfoUserBy method with the arranged parameters + Assert: + - Verify that UserInfoRepo.save() was called once with a User_Info object containing the long strings + - Check that the method returns "ATUALIZADO" + +Validation: + This test ensures that the method can handle and store very long input strings without truncation or errors, which is important for fields that might contain extensive user-generated content. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.dao.DataIntegrityViolationException; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.Optional; + +class UserAccountControllerUpdateInfoUserByTest { + + @Mock + private UserInfoRepository UserInfoRepo; + + @InjectMocks + private UserAccountController userAccountController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void successfulUpdateOfUserInfo() { + int userId = 1; + String photoURL = "http://example.com/photo.jpg"; + String favoritesMusics = "Rock, Pop"; + String gender = "Male"; + String phone = "1234567890"; + String instaURL = "http://instagram.com/user"; + String twitterURL = "http://twitter.com/user"; + String favoritesThings = "Reading, Traveling"; + String result = userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, + instaURL, twitterURL, favoritesThings); + verify(UserInfoRepo, times(1)).save(any(User_Info.class)); + assertEquals("ATUALIZADO", result); + } + + @Test + @Tag("valid") + void updateWithNullValues() { + int userId = 1; + String photoURL = null; + String favoritesMusics = "Jazz"; + String gender = "Female"; + String phone = "9876543210"; + String instaURL = null; + String twitterURL = null; + String favoritesThings = "Cooking"; + String result = userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, + instaURL, twitterURL, favoritesThings); + verify(UserInfoRepo, times(1)).save(argThat(userInfo -> userInfo.getPhotoURL() == null + && userInfo.getInstaURL() == null && userInfo.getTwitterURL() == null)); + assertEquals("ATUALIZADO", result); + } + + @Test + @Tag("valid") + void updateWithEmptyStrings() { + int userId = 1; + String photoURL = "http://example.com/photo.jpg"; + String favoritesMusics = ""; + String gender = "Other"; + String phone = "5555555555"; + String instaURL = "http://instagram.com/user"; + String twitterURL = "http://twitter.com/user"; + String favoritesThings = ""; + String result = userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, + instaURL, twitterURL, favoritesThings); + verify(UserInfoRepo, times(1)).save(argThat( + userInfo -> userInfo.getFavoritesMusics().isEmpty() && userInfo.getFavoritesThings().isEmpty())); + assertEquals("ATUALIZADO", result); + } + + @Test + @Tag("invalid") + void updateWithInvalidUserId() { + int invalidUserId = -1; + String photoURL = "http://example.com/photo.jpg"; + String favoritesMusics = "Classical"; + String gender = "Male"; + String phone = "1231231234"; + String instaURL = "http://instagram.com/user"; + String twitterURL = "http://twitter.com/user"; + String favoritesThings = "Sports"; + doThrow(new DataIntegrityViolationException("Invalid user ID")).when(UserInfoRepo).save(any(User_Info.class)); + assertThrows(DataIntegrityViolationException.class, () -> userAccountController.updateInfoUserBy(invalidUserId, + photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings)); + verify(UserInfoRepo, times(1)).save(any(User_Info.class)); + } + + @Test + @Tag("boundary") + void updateWithVeryLongInputStrings() { + int userId = 1; + String photoURL = "http://example.com/photo.jpg"; + String favoritesMusics = "A".repeat(1000); + String gender = "Female"; + String phone = "9999999999"; + String instaURL = "http://instagram.com/user"; + String twitterURL = "http://twitter.com/user"; + String favoritesThings = "B".repeat(1000); + String result = userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, + instaURL, twitterURL, favoritesThings); + verify(UserInfoRepo, times(1)).save(argThat(userInfo -> userInfo.getFavoritesMusics().length() == 1000 + && userInfo.getFavoritesThings().length() == 1000)); + assertEquals("ATUALIZADO", result); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateUserByIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateUserByIdTest.java new file mode 100644 index 0000000..267aa77 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateUserByIdTest.java @@ -0,0 +1,211 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=updateUserById_45a90e9627 +ROOST_METHOD_SIG_HASH=updateUserById_9cf5a84c94 + +Scenario 1: Successful User Update + +Details: + TestName: successfulUserUpdate + Description: Test the successful update of an existing user's information. + +Execution: + Arrange: + - Mock UserAccRepository + - Create a test User_Credentials object with ID 1 + - Set up the mock to return the test user when findById is called with ID 1 + + Act: + - Call updateUserById with ID "1", new email, password, and username + + Assert: + - Verify that the method returns "Usuário Salvo" + - Verify that the user's email, password, and username were updated + - Verify that the save method was called on the repository + +Validation: + This test ensures that when a valid user ID is provided, the user's information is correctly updated in the database. It verifies the proper functioning of the update logic and the interaction with the repository. + +Scenario 2: Update Non-Existent User + +Details: + TestName: updateNonExistentUser + Description: Test the behavior when attempting to update a user that doesn't exist. + +Execution: + Arrange: + - Mock UserAccRepository + - Set up the mock to return null when findById is called with any ID + + Act: + - Call updateUserById with ID "999", and any email, password, and username + + Assert: + - Verify that the method returns "User não encontrado" + - Verify that the save method was not called on the repository + +Validation: + This test ensures that the method handles non-existent users correctly by returning an appropriate error message and not attempting to save any changes to the database. + +Scenario 3: Invalid ID Format + +Details: + TestName: invalidIdFormat + Description: Test the behavior when an invalid ID format is provided. + +Execution: + Arrange: + - No specific arrangement needed + + Act: + - Call updateUserById with ID "abc", and any email, password, and username + + Assert: + - Verify that a NumberFormatException is thrown + +Validation: + This test ensures that the method properly handles invalid input for the ID parameter by throwing a NumberFormatException, which helps maintain data integrity and prevents processing with incorrect IDs. + +Scenario 4: Empty Fields Update + +Details: + TestName: emptyFieldsUpdate + Description: Test updating a user with empty strings for email, password, and username. + +Execution: + Arrange: + - Mock UserAccRepository + - Create a test User_Credentials object with ID 1 + - Set up the mock to return the test user when findById is called with ID 1 + + Act: + - Call updateUserById with ID "1", and empty strings for email, password, and username + + Assert: + - Verify that the method returns "Usuário Salvo" + - Verify that the user's email, password, and username were updated to empty strings + - Verify that the save method was called on the repository + +Validation: + This test verifies that the method allows updating user fields to empty strings, which may or may not be desired behavior depending on the application's requirements. It helps identify potential issues with data validation or constraints. + +Scenario 5: Null Fields Update + +Details: + TestName: nullFieldsUpdate + Description: Test updating a user with null values for email, password, and username. + +Execution: + Arrange: + - Mock UserAccRepository + - Create a test User_Credentials object with ID 1 + - Set up the mock to return the test user when findById is called with ID 1 + + Act: + - Call updateUserById with ID "1", and null values for email, password, and username + + Assert: + - Verify that the method returns "Usuário Salvo" + - Verify that the user's email, password, and username were updated to null + - Verify that the save method was called on the repository + +Validation: + This test checks how the method handles null input for user fields. Depending on the application's design, this might reveal potential null pointer exceptions or unintended behavior in other parts of the system that rely on these fields. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.Optional; + +class UserAccountControllerUpdateUserByIdTest { + + @Mock + private UserAccRepository UserAccRepo; + + @InjectMocks + private UserAccountController userAccountController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + @Tag("valid") + void successfulUserUpdate() { + User_Credentials testUser = new User_Credentials(); + testUser.setId(1); + when(UserAccRepo.findById(1)).thenReturn(testUser); + String result = userAccountController.updateUserById("1", "new@email.com", "newPassword", "newUsername"); + assertEquals("Usuário Salvo", result); + assertEquals("new@email.com", testUser.getEmail()); + assertEquals("newPassword", testUser.getPassword()); + assertEquals("newUsername", testUser.getUsername()); + verify(UserAccRepo).save(testUser); + } + + @Test + @Tag("invalid") + void updateNonExistentUser() { + when(UserAccRepo.findById(anyInt())).thenReturn(null); + String result = userAccountController.updateUserById("999", "email@test.com", "password", "username"); + assertEquals("User não encontrado", result); + verify(UserAccRepo, never()).save(any()); + } + + @Test + @Tag("invalid") + void invalidIdFormat() { + assertThrows(NumberFormatException.class, + () -> userAccountController.updateUserById("abc", "email@test.com", "password", "username")); + } + + @Test + @Tag("boundary") + void emptyFieldsUpdate() { + User_Credentials testUser = new User_Credentials(); + testUser.setId(1); + when(UserAccRepo.findById(1)).thenReturn(testUser); + String result = userAccountController.updateUserById("1", "", "", ""); + assertEquals("Usuário Salvo", result); + assertEquals("", testUser.getEmail()); + assertEquals("", testUser.getPassword()); + assertEquals("", testUser.getUsername()); + verify(UserAccRepo).save(testUser); + } + + @Test + @Tag("boundary") + void nullFieldsUpdate() { + User_Credentials testUser = new User_Credentials(); + testUser.setId(1); + when(UserAccRepo.findById(1)).thenReturn(testUser); + String result = userAccountController.updateUserById("1", null, null, null); + assertEquals("Usuário Salvo", result); + assertNull(testUser.getEmail()); + assertNull(testUser.getPassword()); + assertNull(testUser.getUsername()); + verify(UserAccRepo).save(testUser); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetForumIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetForumIdTest.java new file mode 100644 index 0000000..9e3fb79 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetForumIdTest.java @@ -0,0 +1,120 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=getForumID_8b51a4f86d +ROOST_METHOD_SIG_HASH=getForumID_2026876329 + +Scenario 1: Retrieve Forum ID Successfully + +Details: + TestName: retrieveForumIDSuccessfully + Description: This test verifies that the getForumID method correctly returns the ForumID value when it has been set. + +Execution: + Arrange: + - Create a new ForumIndexModel object + - Set a known ForumID value using the setForumID method + Act: + - Call the getForumID method + Assert: + - Verify that the returned value matches the set ForumID + +Validation: + This test ensures that the getForumID method accurately retrieves the ForumID value that has been assigned to the object. It confirms the basic functionality of the getter method and validates that the ForumID is correctly stored and accessed within the ForumIndexModel class. + +Scenario 2: Retrieve Default Forum ID + +Details: + TestName: retrieveDefaultForumID + Description: This test checks the behavior of getForumID when no ForumID has been explicitly set. + +Execution: + Arrange: + - Create a new ForumIndexModel object without setting a ForumID + Act: + - Call the getForumID method + Assert: + - Verify that the returned value is the default value for an int (which is 0) + +Validation: + This test verifies that the getForumID method returns the default int value (0) when no ForumID has been set. It's important to understand the default behavior of the method when dealing with uninitialized objects, especially in scenarios where the ForumID might not have been assigned yet. + +Scenario 3: Retrieve Forum ID After Multiple Sets + +Details: + TestName: retrieveForumIDAfterMultipleSets + Description: This test ensures that getForumID returns the most recently set ForumID value after multiple setForumID calls. + +Execution: + Arrange: + - Create a new ForumIndexModel object + - Set an initial ForumID value using setForumID + - Set a new, different ForumID value using setForumID + Act: + - Call the getForumID method + Assert: + - Verify that the returned value matches the most recently set ForumID + +Validation: + This test confirms that the getForumID method always returns the most up-to-date ForumID value, even after multiple updates. It verifies that the setter method correctly updates the internal state and that the getter accurately reflects these changes, which is crucial for maintaining data consistency within the ForumIndexModel class. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Models; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; +import jakarta.persistence.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; + +class ForumIndexModelGetForumIdTest { + + private ForumIndexModel forumIndexModel; + + @BeforeEach + void setUp() { + forumIndexModel = new ForumIndexModel(); + } + + @Test + @Tag("valid") + void retrieveForumIDSuccessfully() { + int expectedForumID = 123; + forumIndexModel.setForumID(expectedForumID); + + int actualForumID = forumIndexModel.getForumID(); + + assertEquals(expectedForumID, actualForumID); + } + + @Test + @Tag("valid") + void retrieveDefaultForumID() { + int defaultForumID = forumIndexModel.getForumID(); + + assertEquals(0, defaultForumID); + } + + @Test + @Tag("valid") + void retrieveForumIDAfterMultipleSets() { + forumIndexModel.setForumID(100); + forumIndexModel.setForumID(200); + int expectedFinalForumID = 300; + forumIndexModel.setForumID(expectedFinalForumID); + + int actualForumID = forumIndexModel.getForumID(); + + assertEquals(expectedFinalForumID, actualForumID); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetForumNameTest.java b/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetForumNameTest.java new file mode 100644 index 0000000..e7c9dc6 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetForumNameTest.java @@ -0,0 +1,121 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=getForumName_5823c0a4e5 +ROOST_METHOD_SIG_HASH=getForumName_7d91ec90d4 + +Scenario 1: Get Forum Name Successfully + +Details: + TestName: getForumNameSuccessfully + Description: Verify that the getForumName method correctly returns the forum name when it has been set. + +Execution: + Arrange: Create a new ForumIndexModel instance and set a forum name using the setForumName method. + Act: Call the getForumName method on the ForumIndexModel instance. + Assert: Check if the returned forum name matches the one that was set. + +Validation: + This test ensures that the getForumName method correctly retrieves the forum name that has been set in the ForumIndexModel object. It verifies the basic functionality of the getter method and confirms that the ForumName field is properly encapsulated. + +Scenario 2: Get Forum Name When Not Set + +Details: + TestName: getForumNameWhenNotSet + Description: Verify the behavior of getForumName when no forum name has been set. + +Execution: + Arrange: Create a new ForumIndexModel instance without setting a forum name. + Act: Call the getForumName method on the ForumIndexModel instance. + Assert: Check if the returned value is null or an empty string, depending on the default behavior of the class. + +Validation: + This test checks how the getForumName method behaves when the ForumName field hasn't been explicitly set. It helps to understand the default state of the ForumName field and ensures that the method handles this case gracefully. + +Scenario 3: Get Forum Name After Multiple Sets + +Details: + TestName: getForumNameAfterMultipleSets + Description: Verify that getForumName returns the most recently set forum name after multiple setForumName calls. + +Execution: + Arrange: Create a ForumIndexModel instance, set an initial forum name, then set a different forum name. + Act: Call the getForumName method on the ForumIndexModel instance. + Assert: Check if the returned forum name matches the most recently set name. + +Validation: + This test ensures that the getForumName method always returns the most up-to-date forum name, even after multiple updates to the ForumName field. It verifies that the setter and getter methods work together correctly to maintain the current state of the forum name. + +Scenario 4: Get Forum Name with Special Characters + +Details: + TestName: getForumNameWithSpecialCharacters + Description: Verify that getForumName correctly handles and returns a forum name containing special characters. + +Execution: + Arrange: Create a ForumIndexModel instance and set a forum name that includes special characters (e.g., "Tech Forum #1 & Q&A"). + Act: Call the getForumName method on the ForumIndexModel instance. + Assert: Check if the returned forum name exactly matches the set name, including all special characters. + +Validation: + This test ensures that the getForumName method can handle and return forum names that contain special characters without any alteration or encoding issues. It's important for maintaining data integrity, especially when forum names might include various symbols or non-alphanumeric characters. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Models; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; +import jakarta.persistence.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; + +class ForumIndexModelGetForumNameTest { + + private ForumIndexModel forumIndexModel; + + @BeforeEach + void setUp() { + forumIndexModel = new ForumIndexModel(); + } + + @Test + @Tag("valid") + void getForumNameSuccessfully() { + String expectedForumName = "Test Forum"; + forumIndexModel.setForumName(expectedForumName); + assertEquals(expectedForumName, forumIndexModel.getForumName()); + } + + @Test + @Tag("valid") + void getForumNameWhenNotSet() { + assertNull(forumIndexModel.getForumName()); + } + + @Test + @Tag("valid") + void getForumNameAfterMultipleSets() { + forumIndexModel.setForumName("Initial Forum"); + String expectedForumName = "Updated Forum"; + forumIndexModel.setForumName(expectedForumName); + assertEquals(expectedForumName, forumIndexModel.getForumName()); + } + + @Test + @Tag("valid") + void getForumNameWithSpecialCharacters() { + String expectedForumName = "Tech Forum #1 & Q&A"; + forumIndexModel.setForumName(expectedForumName); + assertEquals(expectedForumName, forumIndexModel.getForumName()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetIdTest.java new file mode 100644 index 0000000..dc83003 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Models/ForumIndexModelGetIdTest.java @@ -0,0 +1,140 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=getId_582e5a2030 +ROOST_METHOD_SIG_HASH=getId_92e05748b6 + +Scenario 1: Retrieve the ID of a ForumIndexModel object + +Details: + TestName: retrieveId + Description: This test verifies that the getId() method correctly returns the id value of a ForumIndexModel object. + +Execution: + Arrange: Create a ForumIndexModel object and set its id using the setId() method. + Act: Call the getId() method on the ForumIndexModel object. + Assert: Verify that the returned id matches the value that was set. + +Validation: + This test ensures that the getId() method accurately retrieves the id value stored in the ForumIndexModel object. It's crucial for maintaining data integrity and proper identification of forum entries in the system. + +Scenario 2: Retrieve the default ID value + +Details: + TestName: retrieveDefaultId + Description: This test checks if the getId() method returns the default value (likely 0) when the id hasn't been explicitly set. + +Execution: + Arrange: Create a new ForumIndexModel object without setting its id. + Act: Call the getId() method on the ForumIndexModel object. + Assert: Verify that the returned id is the expected default value (typically 0 for int types). + +Validation: + This test confirms that newly created ForumIndexModel objects have a predictable default id value. This is important for distinguishing between initialized and uninitialized objects and for avoiding potential null pointer exceptions. + +Scenario 3: Retrieve ID after multiple updates + +Details: + TestName: retrieveIdAfterUpdates + Description: This test verifies that the getId() method returns the most recent id value after multiple updates. + +Execution: + Arrange: Create a ForumIndexModel object and set its id multiple times using the setId() method. + Act: Call the getId() method on the ForumIndexModel object. + Assert: Verify that the returned id matches the last value that was set. + +Validation: + This test ensures that the getId() method always returns the most up-to-date id value, even after multiple updates. This is crucial for maintaining data consistency, especially in scenarios where forum entries might be modified or transferred between different contexts. + +Scenario 4: Retrieve negative ID value + +Details: + TestName: retrieveNegativeId + Description: This test checks if the getId() method correctly handles and returns a negative id value. + +Execution: + Arrange: Create a ForumIndexModel object and set its id to a negative value using the setId() method. + Act: Call the getId() method on the ForumIndexModel object. + Assert: Verify that the returned id is the same negative value that was set. + +Validation: + While negative ids are unusual in most systems, this test ensures that the getId() method can handle such cases without errors. This improves the robustness of the system and helps catch potential issues with id assignments or database interactions. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Models; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; +import jakarta.persistence.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; + +class ForumIndexModelGetIdTest { + + private ForumIndexModel forumIndexModel; + + @BeforeEach + void setUp() { + forumIndexModel = new ForumIndexModel(); + } + + @Test + @Tag("valid") + void retrieveId() { + forumIndexModel.setId(5); + assertEquals(5, forumIndexModel.getId()); + } + + @Test + @Tag("valid") + void retrieveDefaultId() { + assertEquals(0, forumIndexModel.getId()); + } + + @Test + @Tag("valid") + void retrieveIdAfterUpdates() { + forumIndexModel.setId(10); + forumIndexModel.setId(20); + forumIndexModel.setId(30); + assertEquals(30, forumIndexModel.getId()); + } + + @Test + @Tag("boundary") + void retrieveNegativeId() { + forumIndexModel.setId(-5); + assertEquals(-5, forumIndexModel.getId()); + } + + @Test + @Tag("boundary") + void retrieveMaxIntId() { + forumIndexModel.setId(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, forumIndexModel.getId()); + } + + @Test + @Tag("boundary") + void retrieveMinIntId() { + forumIndexModel.setId(Integer.MIN_VALUE); + assertEquals(Integer.MIN_VALUE, forumIndexModel.getId()); + } + + @Test + @Tag("valid") + void retrieveIdWithParameterizedConstructor() { + ForumIndexModel model = new ForumIndexModel("Test Forum", 1, "Test Description", 100); + assertEquals(0, model.getId()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilGetUserNameTest.java b/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilGetUserNameTest.java new file mode 100644 index 0000000..94083da --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilGetUserNameTest.java @@ -0,0 +1,188 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=getUserName_2f305a5b83 +ROOST_METHOD_SIG_HASH=getUserName_e910087e84 + +Scenario 1: Valid Token with Username + +Details: + TestName: validTokenWithUsername + Description: Test the getUserName method with a valid token containing a username. + +Execution: + Arrange: + - Create a mock Authentication object + - Generate a valid token using the newToken method + Act: + - Call getUserName with the valid token + Assert: + - Verify that the returned username matches the expected username + +Validation: + This test ensures that the getUserName method correctly extracts the username from a valid JWT token. It verifies that the method can parse the claims and return the subject (username) as expected. + +Scenario 2: Invalid Token + +Details: + TestName: invalidToken + Description: Test the getUserName method with an invalid token. + +Execution: + Arrange: + - Create an invalid token string (e.g., "invalid_token") + Act: + - Call getUserName with the invalid token + Assert: + - Verify that the method returns null + +Validation: + This test checks the behavior of getUserName when provided with an invalid token. It ensures that the method handles the error gracefully by returning null when it cannot parse the claims from the token. + +Scenario 3: Expired Token + +Details: + TestName: expiredToken + Description: Test the getUserName method with an expired token. + +Execution: + Arrange: + - Create a mock Authentication object + - Set jwtExpirationMilliseg to a negative value to generate an expired token + - Generate an expired token using the newToken method + Act: + - Call getUserName with the expired token + Assert: + - Verify that the method returns null + +Validation: + This test verifies that getUserName correctly handles expired tokens. Even though the token structure might be valid, an expired token should not return a username, ensuring that the method works in conjunction with token expiration logic. + +Scenario 4: Token with Empty Username + +Details: + TestName: tokenWithEmptyUsername + Description: Test the getUserName method with a token containing an empty username. + +Execution: + Arrange: + - Create a mock Authentication object with an empty username + - Generate a token using the newToken method + Act: + - Call getUserName with the token + Assert: + - Verify that the method returns an empty string + +Validation: + This test ensures that getUserName correctly handles tokens with empty usernames. It verifies that the method doesn't treat an empty username as a null or invalid case, but returns it as is. + +Scenario 5: Null Token Input + +Details: + TestName: nullTokenInput + Description: Test the getUserName method with a null token input. + +Execution: + Arrange: + - No specific arrangement needed + Act: + - Call getUserName with null as the token parameter + Assert: + - Verify that the method returns null + +Validation: + This test checks the behavior of getUserName when provided with a null input. It ensures that the method handles this edge case gracefully by returning null, preventing potential null pointer exceptions in the calling code. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.Security; + +import com.medeiros.SPRINGProject.Models.User_Credentials; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.security.core.Authentication; +import org.springframework.test.util.ReflectionTestUtils; +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.util.Date; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +class JwtUtilGetUserNameTest { + + private JwtUtil jwtUtil; + + @Mock + private Authentication authentication; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + jwtUtil = new JwtUtil(); + ReflectionTestUtils.setField(jwtUtil, "jwtSecret", "testSecretKeyWithAtLeast256BitsForHMACSHA256Algorithm"); + ReflectionTestUtils.setField(jwtUtil, "jwtExpirationMilliseg", 3600000L); + } + + @Test + @Tag("valid") + void validTokenWithUsername() { + User_Credentials user = new User_Credentials(); + user.setUsername("testuser"); + when(authentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(authentication); + String username = jwtUtil.getUserName(token); + assertEquals("testuser", username); + } + + @Test + @Tag("invalid") + void invalidToken() { + String invalidToken = "invalid_token"; + String username = jwtUtil.getUserName(invalidToken); + assertNull(username); + } + + @Test + @Tag("invalid") + void expiredToken() { + User_Credentials user = new User_Credentials(); + user.setUsername("testuser"); + when(authentication.getPrincipal()).thenReturn(user); + ReflectionTestUtils.setField(jwtUtil, "jwtExpirationMilliseg", -1000L); + String expiredToken = jwtUtil.newToken(authentication); + String username = jwtUtil.getUserName(expiredToken); + assertNull(username); + } + + @Test + @Tag("boundary") + void tokenWithEmptyUsername() { + User_Credentials user = new User_Credentials(); + user.setUsername(""); + when(authentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(authentication); + String username = jwtUtil.getUserName(token); + assertEquals("", username); + } + + @Test + @Tag("boundary") + void nullTokenInput() { + String username = jwtUtil.getUserName(null); + assertNull(username); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilIsValidTokenTest.java.invalid b/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilIsValidTokenTest.java.invalid new file mode 100644 index 0000000..86107af --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilIsValidTokenTest.java.invalid @@ -0,0 +1,184 @@ +//This test file is marked invalid as it contains compilation errors. Change the extension to of this file to .java, to manually edit its contents + + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=isValidToken_b61283f593 +ROOST_METHOD_SIG_HASH=isValidToken_97ee283702 + +Scenario 1: Valid Token Test + +Details: + TestName: validTokenTest + Description: This test checks if the method correctly identifies a valid token. + +Execution: + Arrange: + - Create a mock Authentication object + - Generate a valid token using the newToken method + Act: + - Call isValidToken with the generated token + Assert: + - Assert that the method returns true + +Validation: + This test verifies that the isValidToken method correctly identifies a token as valid when it contains a non-null subject (email) and has not yet expired. It's crucial for ensuring that legitimate users with valid tokens can access protected resources. + +Scenario 2: Expired Token Test + +Details: + TestName: expiredTokenTest + Description: This test verifies that the method correctly identifies an expired token as invalid. + +Execution: + Arrange: + - Create a mock Authentication object + - Set jwtExpirationMilliseg to a very small value (e.g., 1 millisecond) + - Generate a token using the newToken method + - Wait for a short period to ensure the token expires + Act: + - Call isValidToken with the expired token + Assert: + - Assert that the method returns false + +Validation: + This test ensures that the isValidToken method correctly identifies expired tokens. It's important for security reasons to reject access attempts with expired tokens, maintaining the integrity of the authentication system. + +Scenario 3: Null Claims Test + +Details: + TestName: nullClaimsTest + Description: This test checks if the method handles a token that results in null claims. + +Execution: + Arrange: + - Mock the getClaims method to return null + Act: + - Call isValidToken with any string as token + Assert: + - Assert that the method returns false + +Validation: + This test verifies that the isValidToken method correctly handles cases where the token cannot be parsed or is invalid, resulting in null claims. It's crucial for robustness and error handling, ensuring the method doesn't throw exceptions for malformed tokens. + +Scenario 4: Null Subject (Email) Test + +Details: + TestName: nullSubjectTest + Description: This test verifies that the method returns false for a token with a null subject. + +Execution: + Arrange: + - Mock the getClaims method to return a Claims object with a null subject + - Set the expiration date of the Claims object to a future date + Act: + - Call isValidToken with any string as token + Assert: + - Assert that the method returns false + +Validation: + This test ensures that the isValidToken method correctly identifies tokens with missing or null subjects (emails) as invalid. It's important for maintaining the integrity of the authentication system by rejecting tokens that lack essential information. + +Scenario 5: Token with Current Time Exactly at Expiration + +Details: + TestName: tokenAtExpirationTest + Description: This test checks the behavior when the current time is exactly at the token's expiration time. + +Execution: + Arrange: + - Create a mock Authentication object + - Generate a token using the newToken method + - Mock the System.currentTimeMillis() to return the exact expiration time of the token + Act: + - Call isValidToken with the generated token + Assert: + - Assert that the method returns false + +Validation: + This test verifies the edge case where the current time is exactly at the token's expiration time. It ensures that the method considers such tokens as expired, maintaining a strict interpretation of the expiration time for security purposes. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Security;import com.medeiros.SPRINGProject.Models.User_Credentials; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.security.core.Authentication; +import org.springframework.test.util.ReflectionTestUtils; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import java.security.Key; + +class JwtUtilIsValidTokenTest { + @InjectMocks + private JwtUtil jwtUtil; + @Mock + private Authentication authentication; + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + ReflectionTestUtils.setField(jwtUtil, "jwtSecret", "testSecretKeyForJwtTokenGenerationAndValidation"); + ReflectionTestUtils.setField(jwtUtil, "jwtExpirationMilliseg", 3600000L); + } + @Test + @Tag("valid") + void validTokenTest() { + User_Credentials user = new User_Credentials(); + user.setUsername("test@example.com"); + when(authentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(authentication); + boolean result = jwtUtil.isValidToken(token); + assertTrue(result); + } + @Test + @Tag("invalid") + void expiredTokenTest() throws InterruptedException { + ReflectionTestUtils.setField(jwtUtil, "jwtExpirationMilliseg", 1L); + User_Credentials user = new User_Credentials(); + user.setUsername("test@example.com"); + when(authentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(authentication); + Thread.sleep(10); // Ensure token expires + boolean result = jwtUtil.isValidToken(token); + assertFalse(result); + } + @Test + @Tag("invalid") + void invalidTokenTest() { + boolean result = jwtUtil.isValidToken("invalidToken"); + assertFalse(result); + } + @Test + @Tag("boundary") + void tokenAtExpirationTest() { + User_Credentials user = new User_Credentials(); + user.setUsername("test@example.com"); + when(authentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(authentication); + + // Set current time to expiration time + long expirationTime = System.currentTimeMillis() + jwtUtil.getJwtExpirationMilliseg(); + Date mockedDate = new Date(expirationTime); + + try (var mockedStatic = mockStatic(System.class)) { + mockedStatic.when(System::currentTimeMillis).thenReturn(expirationTime); + boolean result = jwtUtil.isValidToken(token); + assertFalse(result); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilNewTokenTest.java b/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilNewTokenTest.java new file mode 100644 index 0000000..ab9f374 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Security/JwtUtilNewTokenTest.java @@ -0,0 +1,217 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=newToken_0b98d9bf3a +ROOST_METHOD_SIG_HASH=newToken_275af2b2e1 + +Scenario 1: Successful Token Generation + +Details: + TestName: successfulTokenGeneration + Description: Verify that a valid JWT token is generated when provided with valid authentication. + +Execution: + Arrange: + - Create a mock Authentication object + - Set up a User_Credentials object with a valid username + - Configure the mock Authentication to return the User_Credentials object when getPrincipal() is called + - Set up the JwtUtil object with a valid secret key and expiration time + + Act: + - Call the newToken method with the mock Authentication object + + Assert: + - Verify that the returned token is not null + - Decode the token and check if it contains the correct username + - Verify that the token expiration time is set correctly + +Validation: + This test ensures that the newToken method generates a valid JWT token with the correct claims (subject, issuedAt, expiration) when provided with valid authentication. It's crucial for the application's security and user management. + +Scenario 2: Token Generation with Null Authentication + +Details: + TestName: tokenGenerationWithNullAuthentication + Description: Check the behavior of newToken method when provided with null authentication. + +Execution: + Arrange: + - Set up the JwtUtil object with a valid secret key and expiration time + + Act: + - Call the newToken method with null as the authentication parameter + + Assert: + - Verify that the method returns null or throws an appropriate exception + +Validation: + This test verifies the error handling capability of the newToken method when faced with invalid input. It's important to ensure the method doesn't crash and handles null input gracefully. + +Scenario 3: Token Generation with Invalid User Credentials + +Details: + TestName: tokenGenerationWithInvalidUserCredentials + Description: Test the newToken method's behavior when the authentication object contains invalid user credentials. + +Execution: + Arrange: + - Create a mock Authentication object + - Set up an invalid object (not User_Credentials) as the principal + - Configure the mock Authentication to return the invalid object when getPrincipal() is called + - Set up the JwtUtil object with a valid secret key and expiration time + + Act: + - Call the newToken method with the mock Authentication object + + Assert: + - Verify that the method returns null or throws a ClassCastException + +Validation: + This test ensures that the newToken method handles unexpected types of principal objects correctly. It's crucial for maintaining the integrity of the token generation process and preventing security vulnerabilities. + +Scenario 4: Token Generation with Empty JWT Secret + +Details: + TestName: tokenGenerationWithEmptyJwtSecret + Description: Verify the behavior of newToken method when the JWT secret is empty. + +Execution: + Arrange: + - Create a mock Authentication object with valid User_Credentials + - Set up the JwtUtil object with an empty secret key and valid expiration time + + Act: + - Call the newToken method with the mock Authentication object + + Assert: + - Verify that the method returns null or throws an appropriate exception + +Validation: + This test checks the robustness of the newToken method when essential configuration (JWT secret) is missing. It's important for ensuring the security of the token generation process and preventing the creation of insecure tokens. + +Scenario 5: Token Generation with Expired JWT + +Details: + TestName: tokenGenerationWithExpiredJwt + Description: Test the newToken method's behavior when generating a token with immediate expiration. + +Execution: + Arrange: + - Create a mock Authentication object with valid User_Credentials + - Set up the JwtUtil object with a valid secret key and set jwtExpirationMilliseg to 0 or a negative value + + Act: + - Call the newToken method with the mock Authentication object + + Assert: + - Verify that a token is generated + - Decode the token and check if the expiration time is in the past + +Validation: + This test verifies that the newToken method correctly handles edge cases related to token expiration. It's crucial for understanding how the system behaves with expired tokens and ensures that token expiration is being set correctly. + +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Security; + +import com.medeiros.SPRINGProject.Models.User_Credentials; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.security.core.Authentication; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import java.security.Key; + +class JwtUtilNewTokenTest { + + private JwtUtil jwtUtil; + + @Mock + private Authentication mockAuthentication; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + jwtUtil = new JwtUtil(); + ReflectionTestUtils.setField(jwtUtil, "jwtSecret", "testSecretKeyWithAtLeast256BitsForHmacSHA256"); + ReflectionTestUtils.setField(jwtUtil, "jwtExpirationMilliseg", 3600000L); // 1 + // hour + } + + @Test + @Tag("valid") + void successfulTokenGeneration() { + User_Credentials user = new User_Credentials(); + user.setUsername("testUser"); + when(mockAuthentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(mockAuthentication); + assertNotNull(token); + Claims claims = Jwts.parserBuilder() + .setSigningKey(Keys.hmacShaKeyFor( + ((String) ReflectionTestUtils.getField(jwtUtil, "jwtSecret")).getBytes(StandardCharsets.UTF_8))) + .build() + .parseClaimsJws(token) + .getBody(); + assertEquals("testUser", claims.getSubject()); + assertTrue(claims.getExpiration().after(new Date())); + } + + @Test + @Tag("invalid") + void tokenGenerationWithNullAuthentication() { + String token = jwtUtil.newToken(null); + assertNull(token); + } + + @Test + @Tag("invalid") + void tokenGenerationWithInvalidUserCredentials() { + when(mockAuthentication.getPrincipal()).thenReturn(new Object()); + assertThrows(ClassCastException.class, () -> jwtUtil.newToken(mockAuthentication)); + } + + @Test + @Tag("invalid") + void tokenGenerationWithEmptyJwtSecret() { + ReflectionTestUtils.setField(jwtUtil, "jwtSecret", ""); + User_Credentials user = new User_Credentials(); + user.setUsername("testUser"); + when(mockAuthentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(mockAuthentication); + assertNull(token); + } + + @Test + @Tag("boundary") + void tokenGenerationWithExpiredJwt() { + ReflectionTestUtils.setField(jwtUtil, "jwtExpirationMilliseg", 0L); + User_Credentials user = new User_Credentials(); + user.setUsername("testUser"); + when(mockAuthentication.getPrincipal()).thenReturn(user); + String token = jwtUtil.newToken(mockAuthentication); + assertNotNull(token); + Claims claims = Jwts.parserBuilder() + .setSigningKey(Keys.hmacShaKeyFor( + ((String) ReflectionTestUtils.getField(jwtUtil, "jwtSecret")).getBytes(StandardCharsets.UTF_8))) + .build() + .parseClaimsJws(token) + .getBody(); + assertTrue(claims.getExpiration().before(new Date()) || claims.getExpiration().equals(new Date())); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmBlenderAlgorithmCalcTest.java b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmBlenderAlgorithmCalcTest.java new file mode 100644 index 0000000..e5242aa --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmBlenderAlgorithmCalcTest.java @@ -0,0 +1,211 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=algorithmCalc_e489e5c1fc +ROOST_METHOD_SIG_HASH=algorithmCalc_009085eae1 + +Scenario 1: Empty List Input + +Details: + TestName: emptyListInput + Description: Test the behavior when an empty list is provided as input to the algorithmCalc method. + +Execution: + Arrange: Create an empty list of MusicModel objects. + Act: Call the algorithmCalc method with the empty list. + Assert: Verify that the returned Map is empty. + +Validation: + This test ensures that the method handles empty input correctly by returning an empty Map. It's important to validate edge cases like empty inputs to prevent potential null pointer exceptions or unexpected behavior. + +Scenario 2: Single Music Item + +Details: + TestName: singleMusicItem + Description: Test the calculation for a single music item in the input list. + +Execution: + Arrange: + - Create a MusicModel object with known values for likes and comments. + - Set up the AD object to return known values for rithmPointsByLike and rithmPointsByComents. + Act: Call the algorithmCalc method with a list containing the single MusicModel object. + Assert: + - Verify that the returned Map contains exactly one entry. + - Check that the key matches the music name and the value is the expected sum of like and comment points. + +Validation: + This test verifies the basic functionality of the algorithm for a single item, ensuring that likes and comments are correctly converted to points and summed. + +Scenario 3: Multiple Music Items + +Details: + TestName: multipleMusicItems + Description: Test the calculation for multiple music items in the input list. + +Execution: + Arrange: + - Create multiple MusicModel objects with various combinations of likes and comments. + - Set up the AD object to return known values for rithmPointsByLike and rithmPointsByComents. + Act: Call the algorithmCalc method with a list containing multiple MusicModel objects. + Assert: + - Verify that the returned Map contains the correct number of entries. + - Check that each entry in the Map has the correct music name as key and the expected total points as value. + +Validation: + This test ensures that the method correctly processes multiple items, maintaining accuracy in calculations and proper mapping of results for each music item. + +Scenario 4: Duplicate Music Names + +Details: + TestName: duplicateMusicNames + Description: Test the behavior when the input list contains multiple MusicModel objects with the same music name. + +Execution: + Arrange: + - Create multiple MusicModel objects, some with duplicate music names but different like/comment counts. + - Set up the AD object to return known values for rithmPointsByLike and rithmPointsByComents. + Act: Call the algorithmCalc method with the list containing duplicate music names. + Assert: + - Verify that the returned Map contains only unique keys (music names). + - Check that for duplicate music names, the Map contains the points for the last occurrence in the input list. + +Validation: + This test verifies how the method handles duplicate music names, which is important for understanding the algorithm's behavior with non-unique identifiers. + +Scenario 5: Zero Likes and Comments + +Details: + TestName: zeroLikesAndComments + Description: Test the calculation for music items with zero likes and zero comments. + +Execution: + Arrange: + - Create MusicModel objects with zero likes and zero comments. + - Set up the AD object to return zero points for zero likes and comments. + Act: Call the algorithmCalc method with a list containing these MusicModel objects. + Assert: + - Verify that the returned Map contains the correct entries. + - Check that the point values for these entries are zero. + +Validation: + This test ensures that the method correctly handles edge cases where music items have no engagement (likes or comments), validating that the algorithm doesn't break or produce unexpected results in such scenarios. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.algorithm; + +import com.medeiros.SPRINGProject.Models.MusicModel; +import com.medeiros.SPRINGProject.utils.hashMapFunctions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; + +class AlgorithmBlenderAlgorithmCalcTest { + + private algorithmBlender blender; + + @Mock + private algorithmData AD; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + blender = new algorithmBlender(); + blender.AD = AD; + } + + @Test + @Tag("valid") + void emptyListInput() { + List emptyList = new ArrayList<>(); + Map result = blender.algorithmCalc(emptyList); + assertTrue(result.isEmpty()); + } + + @Test + @Tag("valid") + void singleMusicItem() { + MusicModel music = new MusicModel(); + music.setMusicName("Test Song"); + music.setNumberOfLikes(100); + music.setNumberOfComents(50); + when(AD.rithmPointsByLike(100)).thenReturn(1000); + when(AD.rithmPointsByComents(50)).thenReturn(750); + List singleItemList = List.of(music); + Map result = blender.algorithmCalc(singleItemList); + assertEquals(1, result.size()); + assertEquals(1750, result.get("Test Song")); + } + + @Test + @Tag("valid") + void multipleMusicItems() { + MusicModel music1 = new MusicModel(); + music1.setMusicName("Song 1"); + music1.setNumberOfLikes(100); + music1.setNumberOfComents(50); + MusicModel music2 = new MusicModel(); + music2.setMusicName("Song 2"); + music2.setNumberOfLikes(200); + music2.setNumberOfComents(100); + when(AD.rithmPointsByLike(100)).thenReturn(1000); + when(AD.rithmPointsByComents(50)).thenReturn(750); + when(AD.rithmPointsByLike(200)).thenReturn(2000); + when(AD.rithmPointsByComents(100)).thenReturn(1500); + List multipleItemList = List.of(music1, music2); + Map result = blender.algorithmCalc(multipleItemList); + assertEquals(2, result.size()); + assertEquals(1750, result.get("Song 1")); + assertEquals(3500, result.get("Song 2")); + } + + @Test + @Tag("valid") + void duplicateMusicNames() { + MusicModel music1 = new MusicModel(); + music1.setMusicName("Duplicate Song"); + music1.setNumberOfLikes(100); + music1.setNumberOfComents(50); + MusicModel music2 = new MusicModel(); + music2.setMusicName("Duplicate Song"); + music2.setNumberOfLikes(200); + music2.setNumberOfComents(100); + when(AD.rithmPointsByLike(100)).thenReturn(1000); + when(AD.rithmPointsByComents(50)).thenReturn(750); + when(AD.rithmPointsByLike(200)).thenReturn(2000); + when(AD.rithmPointsByComents(100)).thenReturn(1500); + List duplicateNameList = List.of(music1, music2); + Map result = blender.algorithmCalc(duplicateNameList); + assertEquals(1, result.size()); + assertEquals(3500, result.get("Duplicate Song")); + } + + @Test + @Tag("boundary") + void zeroLikesAndComments() { + MusicModel music = new MusicModel(); + music.setMusicName("Zero Engagement"); + music.setNumberOfLikes(0); + music.setNumberOfComents(0); + when(AD.rithmPointsByLike(0)).thenReturn(0); + when(AD.rithmPointsByComents(0)).thenReturn(0); + List zeroEngagementList = List.of(music); + Map result = blender.algorithmCalc(zeroEngagementList); + assertEquals(1, result.size()); + assertEquals(0, result.get("Zero Engagement")); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataGetRithmPointsTest.java b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataGetRithmPointsTest.java new file mode 100644 index 0000000..fec6566 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataGetRithmPointsTest.java @@ -0,0 +1,160 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=getRithmPoints_82f961bd0d +ROOST_METHOD_SIG_HASH=getRithmPoints_728e09b79f + +Scenario 1: Get Rithm Points When Points Are Set + +Details: + TestName: getRithmPointsWhenSet + Description: This test verifies that the getRithmPoints method returns the correct value when rithmPoints have been set. + +Execution: + Arrange: Create an instance of algorithmData and set rithmPoints to a specific value. + Act: Call the getRithmPoints method. + Assert: Verify that the returned value matches the set value. + +Validation: + This test ensures that the getRithmPoints method correctly retrieves the rithmPoints value that has been set. It's crucial for verifying the basic functionality of getting the user's Rithm points. + +Scenario 2: Get Rithm Points When Points Are Not Set (Default Value) + +Details: + TestName: getRithmPointsWhenNotSet + Description: This test checks the behavior of getRithmPoints when rithmPoints haven't been explicitly set. + +Execution: + Arrange: Create a new instance of algorithmData without setting rithmPoints. + Act: Call the getRithmPoints method. + Assert: Verify that the returned value is 0 (assuming 0 is the default value for int fields). + +Validation: + This test verifies that getRithmPoints returns the expected default value when rithmPoints haven't been set. It's important for understanding the initial state of a user's Rithm points. + +Scenario 3: Get Rithm Points After Multiple Updates + +Details: + TestName: getRithmPointsAfterMultipleUpdates + Description: This test ensures that getRithmPoints returns the most recent value after multiple updates to rithmPoints. + +Execution: + Arrange: Create an instance of algorithmData, set rithmPoints to an initial value, then update it multiple times. + Act: Call the getRithmPoints method. + Assert: Verify that the returned value matches the last set value. + +Validation: + This test confirms that getRithmPoints always returns the most up-to-date value of rithmPoints, even after multiple updates. It's critical for ensuring the accuracy of the user's current Rithm points. + +Scenario 4: Get Rithm Points for Blacklisted User + +Details: + TestName: getRithmPointsForBlacklistedUser + Description: This test verifies the behavior of getRithmPoints when the user is blacklisted. + +Execution: + Arrange: Create an instance of algorithmData, set rithmPoints to a non-zero value, and set black_list to true. + Act: Call the getRithmPoints method. + Assert: Verify that the returned value matches the set value (assuming blacklisting doesn't affect rithmPoints). + +Validation: + This test checks if the getRithmPoints method functions correctly for blacklisted users. It's important to ensure that a user's Rithm points are still accessible even if they are blacklisted. + +Scenario 5: Get Rithm Points for Blocked User + +Details: + TestName: getRithmPointsForBlockedUser + Description: This test checks the behavior of getRithmPoints when the user is blocked. + +Execution: + Arrange: Create an instance of algorithmData, set rithmPoints to a non-zero value, and set blocked to true. + Act: Call the getRithmPoints method. + Assert: Verify that the returned value matches the set value (assuming blocking doesn't affect rithmPoints). + +Validation: + This test ensures that the getRithmPoints method works correctly for blocked users. It's crucial to verify that a user's Rithm points can still be retrieved even if their account is blocked. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.algorithm; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; + +class AlgorithmDataGetRithmPointsTest { + + private algorithmData algorithm; + + @BeforeEach + void setUp() { + algorithm = new algorithmData(); + } + + @Test + @Tag("valid") + void getRithmPointsWhenSet() { + algorithm.setRithmPoints(100); + assertEquals(100, algorithm.getRithmPoints()); + } + + @Test + @Tag("valid") + void getRithmPointsWhenNotSet() { + assertEquals(0, algorithm.getRithmPoints()); + } + + @Test + @Tag("valid") + void getRithmPointsAfterMultipleUpdates() { + algorithm.setRithmPoints(50); + algorithm.setRithmPoints(75); + algorithm.setRithmPoints(100); + assertEquals(100, algorithm.getRithmPoints()); + } + + @Test + @Tag("valid") + void getRithmPointsForBlacklistedUser() { + algorithm.setRithmPoints(200); + algorithm.setBlack_list(true); + assertEquals(200, algorithm.getRithmPoints()); + } + + @Test + @Tag("valid") + void getRithmPointsForBlockedUser() { + algorithm.setRithmPoints(150); + algorithm.setBlocked(true); + assertEquals(150, algorithm.getRithmPoints()); + } + + @Test + @Tag("boundary") + void getRithmPointsWithMaxValue() { + algorithm.setRithmPoints(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, algorithm.getRithmPoints()); + } + + @Test + @Tag("boundary") + void getRithmPointsWithMinValue() { + algorithm.setRithmPoints(Integer.MIN_VALUE); + assertEquals(Integer.MIN_VALUE, algorithm.getRithmPoints()); + } + + @Test + @Tag("valid") + void getRithmPointsAfterReset() { + algorithm.setRithmPoints(100); + algorithm.setRithmPoints(0); + assertEquals(0, algorithm.getRithmPoints()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataIsBlackListTest.java b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataIsBlackListTest.java new file mode 100644 index 0000000..dad1811 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataIsBlackListTest.java @@ -0,0 +1,144 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=isBlack_list_560ae9db06 +ROOST_METHOD_SIG_HASH=isBlack_list_4614434c3f + +Scenario 1: Test when black_list is true + +Details: + TestName: blackListTrue + Description: Verify that isBlack_list() returns true when the black_list field is set to true. + +Execution: + Arrange: Create an instance of algorithmData and set black_list to true. + Act: Call the isBlack_list() method. + Assert: Verify that the returned value is true. + +Validation: + This test ensures that the isBlack_list() method correctly reflects the state of the black_list field when it is set to true. It's important for accurately determining if a user or entity is on the black list. + +Scenario 2: Test when black_list is false + +Details: + TestName: blackListFalse + Description: Verify that isBlack_list() returns false when the black_list field is set to false. + +Execution: + Arrange: Create an instance of algorithmData and set black_list to false. + Act: Call the isBlack_list() method. + Assert: Verify that the returned value is false. + +Validation: + This test ensures that the isBlack_list() method correctly reflects the state of the black_list field when it is set to false. It's crucial for confirming that users or entities not on the black list are correctly identified. + +Scenario 3: Test default value of black_list + +Details: + TestName: defaultBlackListValue + Description: Verify that isBlack_list() returns the default value of black_list when it hasn't been explicitly set. + +Execution: + Arrange: Create a new instance of algorithmData without setting the black_list field. + Act: Call the isBlack_list() method. + Assert: Verify that the returned value matches the expected default value (likely false, but this depends on how the class is implemented). + +Validation: + This test ensures that the isBlack_list() method behaves correctly when the black_list field hasn't been explicitly set. It's important for understanding the default state of entities in the system. + +Scenario 4: Test consistency after multiple calls + +Details: + TestName: consistencyAfterMultipleCalls + Description: Verify that isBlack_list() returns consistent results when called multiple times without changing the black_list field. + +Execution: + Arrange: Create an instance of algorithmData and set black_list to a specific value (true or false). + Act: Call the isBlack_list() method multiple times. + Assert: Verify that all calls return the same value. + +Validation: + This test ensures that the isBlack_list() method provides consistent results across multiple invocations. It's crucial for the reliability of the system, especially in scenarios where the method might be called frequently. + +Scenario 5: Test interaction with setBlack_list method + +Details: + TestName: interactionWithSetBlackList + Description: Verify that isBlack_list() reflects changes made using the setBlack_list() method. + +Execution: + Arrange: Create an instance of algorithmData. + Act: + 1. Call setBlack_list(true) and then call isBlack_list(). + 2. Call setBlack_list(false) and then call isBlack_list() again. + Assert: Verify that the first call returns true and the second call returns false. + +Validation: + This test ensures that the isBlack_list() method correctly reflects changes made to the black_list field via the setBlack_list() method. It's important for verifying the proper interaction between getter and setter methods, which is crucial for maintaining the object's state consistency. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.algorithm; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; + +class AlgorithmDataIsBlackListTest { + + private algorithmData algorithm; + + @BeforeEach + void setUp() { + algorithm = new algorithmData(); + } + + @Test + @Tag("valid") + void blackListTrue() { + algorithm.setBlack_list(true); + assertTrue(algorithm.isBlack_list()); + } + + @Test + @Tag("valid") + void blackListFalse() { + algorithm.setBlack_list(false); + assertFalse(algorithm.isBlack_list()); + } + + @Test + @Tag("boundary") + void defaultBlackListValue() { + assertFalse(algorithm.isBlack_list()); + } + + @Test + @Tag("valid") + void consistencyAfterMultipleCalls() { + algorithm.setBlack_list(true); + assertTrue(algorithm.isBlack_list()); + assertTrue(algorithm.isBlack_list()); + assertTrue(algorithm.isBlack_list()); + algorithm.setBlack_list(false); + assertFalse(algorithm.isBlack_list()); + assertFalse(algorithm.isBlack_list()); + assertFalse(algorithm.isBlack_list()); + } + + @Test + @Tag("integration") + void interactionWithSetBlackList() { + algorithm.setBlack_list(true); + assertTrue(algorithm.isBlack_list()); + algorithm.setBlack_list(false); + assertFalse(algorithm.isBlack_list()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataIsBlockedTest.java b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataIsBlockedTest.java new file mode 100644 index 0000000..4c7c45d --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataIsBlockedTest.java @@ -0,0 +1,115 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=isBlocked_47b7fd7aa5 +ROOST_METHOD_SIG_HASH=isBlocked_75b5602366 + +Scenario 1: Test when user is blocked + +Details: + TestName: blockedUserReturnsTrue + Description: Verify that the isBlocked() method returns true when the user is blocked. + +Execution: + Arrange: Create an instance of algorithmData and set the blocked status to true. + Act: Call the isBlocked() method. + Assert: Verify that the method returns true. + +Validation: + This test ensures that the isBlocked() method correctly identifies a blocked user. It's crucial for implementing access control and user management features in the application. + +Scenario 2: Test when user is not blocked + +Details: + TestName: nonBlockedUserReturnsFalse + Description: Verify that the isBlocked() method returns false when the user is not blocked. + +Execution: + Arrange: Create an instance of algorithmData and set the blocked status to false. + Act: Call the isBlocked() method. + Assert: Verify that the method returns false. + +Validation: + This test confirms that the isBlocked() method correctly identifies a non-blocked user. It's essential for ensuring that active users maintain proper access to the system. + +Scenario 3: Test default blocked status + +Details: + TestName: defaultBlockedStatus + Description: Verify the default blocked status when an algorithmData instance is created without explicitly setting the blocked status. + +Execution: + Arrange: Create a new instance of algorithmData without modifying the blocked status. + Act: Call the isBlocked() method. + Assert: Verify the returned value (which depends on the default initialization of the 'blocked' field). + +Validation: + This test checks the default behavior of the isBlocked() method for newly created objects. It's important for understanding the initial state of user accounts and ensuring consistent behavior across the application. + +Scenario 4: Test blocked status after multiple changes + +Details: + TestName: blockedStatusAfterMultipleChanges + Description: Verify that the isBlocked() method returns the correct status after the blocked field is changed multiple times. + +Execution: + Arrange: Create an instance of algorithmData, set blocked to true, then to false, and finally back to true. + Act: Call the isBlocked() method. + Assert: Verify that the method returns true. + +Validation: + This test ensures that the isBlocked() method accurately reflects the current blocked status, even after multiple changes. It's crucial for maintaining the integrity of user status throughout various operations in the system. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.algorithm; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; + +class AlgorithmDataIsBlockedTest { + + private algorithmData testData; + + @BeforeEach + void setUp() { + testData = new algorithmData(); + } + + @Test + @Tag("valid") + void blockedUserReturnsTrue() { + testData.setBlocked(true); + assertTrue(testData.isBlocked()); + } + + @Test + @Tag("valid") + void nonBlockedUserReturnsFalse() { + testData.setBlocked(false); + assertFalse(testData.isBlocked()); + } + + @Test + @Tag("boundary") + void defaultBlockedStatus() { + assertFalse(testData.isBlocked()); + } + + @Test + @Tag("valid") + void blockedStatusAfterMultipleChanges() { + testData.setBlocked(true); + testData.setBlocked(false); + testData.setBlocked(true); + assertTrue(testData.isBlocked()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataRithmPointsByComentsTest.java b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataRithmPointsByComentsTest.java new file mode 100644 index 0000000..38d26bb --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataRithmPointsByComentsTest.java @@ -0,0 +1,135 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=rithmPointsByComents_bf0560ce74 +ROOST_METHOD_SIG_HASH=rithmPointsByComents_16f69f99ca + +Scenario 1: Calculate Rithm Points for Zero Comments + +Details: + TestName: calculateRithmPointsForZeroComments + Description: This test checks if the method correctly calculates Rithm points when there are zero comments. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByComents method with 0 as the parameter. + Assert: Verify that the returned value is 0. + +Validation: + This test ensures that the method handles the edge case of zero comments correctly. It's important to verify that no points are awarded when there are no comments, maintaining the integrity of the point system. + +Scenario 2: Calculate Rithm Points for Positive Number of Comments + +Details: + TestName: calculateRithmPointsForPositiveComments + Description: This test verifies the correct calculation of Rithm points for a positive number of comments. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByComents method with 10 as the parameter. + Assert: Verify that the returned value is 150 (10 * 15). + +Validation: + This test confirms that the method accurately calculates Rithm points for a typical use case with a positive number of comments. It ensures that the multiplication factor of 15 is correctly applied. + +Scenario 3: Calculate Rithm Points for Large Number of Comments + +Details: + TestName: calculateRithmPointsForLargeNumberOfComments + Description: This test checks the method's behavior with a large number of comments to ensure no overflow occurs. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByComents method with 1000000 as the parameter. + Assert: Verify that the returned value is 15000000 (1000000 * 15). + +Validation: + This test ensures that the method can handle large numbers without overflow. It's crucial to verify that the calculation remains accurate even with a high volume of comments, which could occur in popular posts or over time. + +Scenario 4: Calculate Rithm Points for Negative Number of Comments + +Details: + TestName: calculateRithmPointsForNegativeComments + Description: This test verifies how the method handles negative number of comments, which is an invalid input. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByComents method with -5 as the parameter. + Assert: Verify that the returned value is -75 (-5 * 15). + +Validation: + While negative comments are not a valid real-world scenario, this test checks how the method behaves with unexpected input. It's important to note that the current implementation allows negative results, which might not be desirable. This test could highlight a need for input validation or error handling in the method. + +Scenario 5: Verify Rithm Points Calculation is Independent of User Status + +Details: + TestName: verifyRithmPointsCalculationIndependentOfUserStatus + Description: This test ensures that the Rithm points calculation is not affected by the user's black_list or blocked status. + +Execution: + Arrange: + Create an instance of algorithmData class. + Set black_list to true using setBlack_list method. + Set blocked to true using setBlocked method. + Act: Call rithmPointsByComents method with 5 as the parameter. + Assert: Verify that the returned value is 75 (5 * 15). + +Validation: + This test confirms that the Rithm points calculation is based solely on the number of comments and is not influenced by the user's status (black_listed or blocked). It's crucial to ensure that the point calculation remains consistent regardless of other user attributes. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.algorithm; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; + +class AlgorithmDataRithmPointsByComentsTest { + + private algorithmData algorithmData; + + @BeforeEach + void setUp() { + algorithmData = new algorithmData(); + } + + @Test + @Tag("boundary") + void calculateRithmPointsForZeroComments() { + assertEquals(0, algorithmData.rithmPointsByComents(0)); + } + + @Test + @Tag("valid") + void calculateRithmPointsForPositiveComments() { + assertEquals(150, algorithmData.rithmPointsByComents(10)); + } + + @Test + @Tag("boundary") + void calculateRithmPointsForLargeNumberOfComments() { + assertEquals(15000000, algorithmData.rithmPointsByComents(1000000)); + } + + @Test + @Tag("invalid") + void calculateRithmPointsForNegativeComments() { + assertEquals(-75, algorithmData.rithmPointsByComents(-5)); + } + + @Test + @Tag("integration") + void verifyRithmPointsCalculationIndependentOfUserStatus() { + algorithmData.setBlack_list(true); + algorithmData.setBlocked(true); + assertEquals(75, algorithmData.rithmPointsByComents(5)); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataRithmPointsByLikeTest.java b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataRithmPointsByLikeTest.java new file mode 100644 index 0000000..789d186 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/algorithm/AlgorithmDataRithmPointsByLikeTest.java @@ -0,0 +1,135 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=rithmPointsByLike_f1d922798a +ROOST_METHOD_SIG_HASH=rithmPointsByLike_817b4e8687 + +Scenario 1: Positive likes calculation + +Details: + TestName: positiveRithmPointsCalculation + Description: Verify that the method correctly calculates Rithm points for a positive number of likes. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByLike method with a positive number of likes (e.g., 5). + Assert: Check if the returned value equals 50 (5 * 10). + +Validation: + This test ensures that the method accurately calculates Rithm points for a typical positive scenario. It verifies the core functionality of the method, which is to multiply the number of likes by 10. + +Scenario 2: Zero likes calculation + +Details: + TestName: zeroLikesCalculation + Description: Verify that the method correctly handles zero likes. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByLike method with zero likes. + Assert: Check if the returned value equals 0. + +Validation: + This test confirms that the method correctly handles the edge case of zero likes, ensuring it returns zero points as expected. + +Scenario 3: Large number of likes calculation + +Details: + TestName: largeNumberOfLikesCalculation + Description: Verify that the method correctly calculates Rithm points for a large number of likes. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByLike method with a large number of likes (e.g., 1000000). + Assert: Check if the returned value equals 10000000 (1000000 * 10). + +Validation: + This test ensures that the method can handle large input values without overflow or precision issues, validating its robustness for extreme cases. + +Scenario 4: Negative likes handling + +Details: + TestName: negativeLikesHandling + Description: Verify how the method handles negative number of likes. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: Call rithmPointsByLike method with a negative number of likes (e.g., -5). + Assert: Check if the returned value equals -50 (-5 * 10). + +Validation: + This test verifies the behavior of the method when given negative input. While negative likes may not be a valid real-world scenario, it's important to understand how the method responds to such input for completeness of testing. + +Scenario 5: Integration with rithmPoints field + +Details: + TestName: integrationWithRithmPointsField + Description: Verify that the calculated Rithm points can be correctly stored in the rithmPoints field. + +Execution: + Arrange: Create an instance of algorithmData class. + Act: + 1. Call rithmPointsByLike method with a number of likes (e.g., 7). + 2. Use setRithmPoints method to store the result. + 3. Use getRithmPoints method to retrieve the stored value. + Assert: Check if the retrieved value equals 70 (7 * 10). + +Validation: + This test ensures that the calculated Rithm points can be correctly stored in and retrieved from the rithmPoints field, validating the integration between the method and the class's state. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.algorithm; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; + +class AlgorithmDataRithmPointsByLikeTest { + + private algorithmData algorithm; + + @BeforeEach + void setUp() { + algorithm = new algorithmData(); + } + + @Test + @Tag("valid") + void positiveRithmPointsCalculation() { + assertEquals(50, algorithm.rithmPointsByLike(5)); + } + + @Test + @Tag("boundary") + void zeroLikesCalculation() { + assertEquals(0, algorithm.rithmPointsByLike(0)); + } + + @Test + @Tag("boundary") + void largeNumberOfLikesCalculation() { + assertEquals(10000000, algorithm.rithmPointsByLike(1000000)); + } + + @Test + @Tag("invalid") + void negativeLikesHandling() { + assertEquals(-50, algorithm.rithmPointsByLike(-5)); + } + + @Test + @Tag("integration") + void integrationWithRithmPointsField() { + int calculatedPoints = algorithm.rithmPointsByLike(7); + algorithm.setRithmPoints(calculatedPoints); + assertEquals(70, algorithm.getRithmPoints()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/medeiros/SPRINGProject/utils/HashMapFunctionsOrdenarHashMapPorValorTest.java b/src/test/java/com/medeiros/SPRINGProject/utils/HashMapFunctionsOrdenarHashMapPorValorTest.java new file mode 100644 index 0000000..58ba8e0 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/utils/HashMapFunctionsOrdenarHashMapPorValorTest.java @@ -0,0 +1,185 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test javabedrock using AI Type AWS Bedrock Runtime AI and AI Model eu.anthropic.claude-3-5-sonnet-20240620-v1:0 + +ROOST_METHOD_HASH=ordenarHashMapPorValor_29e282f5b3 +ROOST_METHOD_SIG_HASH=ordenarHashMapPorValor_afd4884fe1 + +Scenario 1: Sort a HashMap with Multiple Entries in Descending Order by Value + +Details: + TestName: sortHashMapWithMultipleEntries + Description: Test that the method correctly sorts a HashMap with multiple entries in descending order based on their integer values. + +Execution: + Arrange: Create a HashMap with multiple string keys and integer values. + Act: Call the ordenarHashMapPorValor method with the created HashMap. + Assert: Verify that the returned HashMap is sorted in descending order based on the integer values. + +Validation: + This test ensures that the method can handle a typical use case with multiple entries and correctly sort them. It validates that the sorting logic works as expected for a standard input. + +Scenario 2: Sort an Empty HashMap + +Details: + TestName: sortEmptyHashMap + Description: Test the behavior of the method when given an empty HashMap as input. + +Execution: + Arrange: Create an empty HashMap. + Act: Call the ordenarHashMapPorValor method with the empty HashMap. + Assert: Verify that the returned HashMap is also empty. + +Validation: + This test checks how the method handles an edge case of an empty input. It ensures that the method doesn't throw an exception and returns an empty HashMap as expected. + +Scenario 3: Sort a HashMap with a Single Entry + +Details: + TestName: sortHashMapWithSingleEntry + Description: Test the method's behavior when given a HashMap containing only one entry. + +Execution: + Arrange: Create a HashMap with a single key-value pair. + Act: Call the ordenarHashMapPorValor method with this HashMap. + Assert: Verify that the returned HashMap contains the same single entry. + +Validation: + This test case verifies that the method correctly handles a HashMap with just one entry, ensuring it doesn't modify the input and returns it as is. + +Scenario 4: Sort a HashMap with Duplicate Values + +Details: + TestName: sortHashMapWithDuplicateValues + Description: Test the method's behavior when the input HashMap contains entries with duplicate integer values. + +Execution: + Arrange: Create a HashMap with multiple entries, some having the same integer values. + Act: Call the ordenarHashMapPorValor method with this HashMap. + Assert: Verify that the returned HashMap is sorted in descending order by value, with entries having the same value maintaining their relative order. + +Validation: + This test ensures that the method correctly handles cases where multiple entries have the same value, maintaining stability in the sorting process. + +Scenario 5: Sort a HashMap with Negative and Positive Values + +Details: + TestName: sortHashMapWithMixedValues + Description: Test the method's ability to sort a HashMap containing both negative and positive integer values. + +Execution: + Arrange: Create a HashMap with entries having a mix of negative and positive integer values. + Act: Call the ordenarHashMapPorValor method with this HashMap. + Assert: Verify that the returned HashMap is correctly sorted in descending order, with positive values appearing before negative values. + +Validation: + This test validates that the method can handle a range of integer values, including negatives, and sort them correctly in descending order. + +Scenario 6: Verify Preservation of Original HashMap + +Details: + TestName: verifyOriginalHashMapUnchanged + Description: Test that the original HashMap passed to the method remains unchanged after sorting. + +Execution: + Arrange: Create a HashMap and make a deep copy of it. + Act: Call the ordenarHashMapPorValor method with the original HashMap. + Assert: Verify that the original HashMap is unchanged by comparing it with the deep copy. + +Validation: + This test ensures that the method does not modify the input HashMap, adhering to the principle of non-destructive operations on input data. + +*/ + +// ********RoostGPT******** + +package com.medeiros.SPRINGProject.utils; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import static org.junit.jupiter.api.Assertions.*; +import java.util.*; +import org.junit.jupiter.api.*; + +class HashMapFunctionsOrdenarHashMapPorValorTest { + + @Test + @Tag("valid") + void sortHashMapWithMultipleEntries() { + HashMap input = new HashMap<>(); + input.put("A", 3); + input.put("B", 1); + input.put("C", 4); + input.put("D", 2); + HashMap sorted = hashMapFunctions.ordenarHashMapPorValor(input); + List values = new ArrayList<>(sorted.values()); + for (int i = 0; i < values.size() - 1; i++) { + assertTrue(values.get(i) >= values.get(i + 1)); + } + } + + @Test + @Tag("boundary") + void sortEmptyHashMap() { + HashMap input = new HashMap<>(); + HashMap sorted = hashMapFunctions.ordenarHashMapPorValor(input); + assertTrue(sorted.isEmpty()); + } + + @Test + @Tag("boundary") + void sortHashMapWithSingleEntry() { + HashMap input = new HashMap<>(); + input.put("A", 1); + HashMap sorted = hashMapFunctions.ordenarHashMapPorValor(input); + assertEquals(1, sorted.size()); + assertTrue(sorted.containsKey("A")); + assertEquals(1, sorted.get("A")); + } + + @Test + @Tag("valid") + void sortHashMapWithDuplicateValues() { + HashMap input = new HashMap<>(); + input.put("A", 3); + input.put("B", 2); + input.put("C", 3); + input.put("D", 1); + HashMap sorted = hashMapFunctions.ordenarHashMapPorValor(input); + List values = new ArrayList<>(sorted.values()); + for (int i = 0; i < values.size() - 1; i++) { + assertTrue(values.get(i) >= values.get(i + 1)); + } + } + + @Test + @Tag("valid") + void sortHashMapWithMixedValues() { + HashMap input = new HashMap<>(); + input.put("A", -3); + input.put("B", 2); + input.put("C", 0); + input.put("D", 5); + input.put("E", -1); + HashMap sorted = hashMapFunctions.ordenarHashMapPorValor(input); + List values = new ArrayList<>(sorted.values()); + for (int i = 0; i < values.size() - 1; i++) { + assertTrue(values.get(i) >= values.get(i + 1)); + } + } + + @Test + @Tag("valid") + void verifyOriginalHashMapUnchanged() { + HashMap original = new HashMap<>(); + original.put("A", 3); + original.put("B", 1); + original.put("C", 4); + original.put("D", 2); + HashMap copy = new HashMap<>(original); + hashMapFunctions.ordenarHashMapPorValor(original); + assertEquals(copy, original); + } + +} \ No newline at end of file