From 4bab0c04effed83e2faf5635a741e74c376bf8d6 Mon Sep 17 00:00:00 2001 From: roost-io Date: Thu, 20 Jun 2024 09:34:51 +0000 Subject: [PATCH] Unit test generated by RoostGPT Using AI Model claude-3-opus-20240229 --- pom.xml | 239 +++++++++++------- .../ForumControllerCreateForumIndexTest.java | 168 ++++++++++++ .../ForumControllerNewMessageTest.java | 200 +++++++++++++++ .../ForumControllerShowMessagesTest.java | 136 ++++++++++ ...erAccountControllerDeleteUserByIdTest.java | 163 ++++++++++++ ...UserAccountControllerFindUserByIdTest.java | 152 +++++++++++ ...AccountControllerUpdateInfoUserByTest.java | 209 +++++++++++++++ ...erAccountControllerUpdateUserByIdTest.java | 219 ++++++++++++++++ .../Models/CommentsModelGetIdTest.java | 132 ++++++++++ .../Models/CommentsModelGetMusicIdTest.java | 117 +++++++++ .../Models/CommentsModelSetIdTest.java | 132 ++++++++++ 11 files changed, 1771 insertions(+), 96 deletions(-) create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerCreateForumIndexTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerNewMessageTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerShowMessagesTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerDeleteUserByIdTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerFindUserByIdTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateInfoUserByTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateUserByIdTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetIdTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetMusicIdTest.java create mode 100644 src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelSetIdTest.java diff --git a/pom.xml b/pom.xml index d5e071f..9641a6f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,96 +1,143 @@ - - - 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 + + + io.spring.javaformat + spring-javaformat-formatter + 0.0.40 + + + + + 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.7 + + + + 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 + + + + + \ 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..e3fa263 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerCreateForumIndexTest.java @@ -0,0 +1,168 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=createForumIndex_b589032131 +ROOST_METHOD_SIG_HASH=createForumIndex_617623f3d0 + +Here are some JUnit test scenarios for the createForumIndex method: + +Scenario 1: Successfully create a new forum + +Details: + TestName: createNewForumSuccessfully + Description: This test checks if a new forum can be created successfully with valid input parameters. +Execution: + Arrange: + - Set up a mock ForumIndexRepository that returns the saved ForumIndexModel when save is called. + - Prepare valid input parameters for nameForum, forumDescription, and userId. + Act: + - Invoke the createForumIndex method with the prepared input parameters. + Assert: + - Verify that ForumIndexRepo.save is called with the expected ForumIndexModel. + - Assert that the method returns the string "Forum criado". +Validation: + The assertion verifies that the new forum is saved correctly in the repository and the method returns the expected success message. This test ensures that the basic functionality of creating a new forum works as intended. + +Scenario 2: Attempt to create a forum with missing parameters + +Details: + TestName: createForumWithMissingParameters + Description: This test checks if the method handles missing request parameters gracefully and returns an appropriate error response. +Execution: + Arrange: + - Prepare input parameters with missing nameForum or forumDescription. + Act: + - Invoke the createForumIndex method with the prepared input parameters. + Assert: + - Verify that the method throws a MissingServletRequestParameterException. + - Assert that the exception message indicates the missing parameter. +Validation: + The assertion verifies that the method validates the presence of required parameters and throws an appropriate exception when they are missing. This test ensures that the method handles invalid input and provides meaningful error messages. + +Scenario 3: Create a forum with an invalid user ID + +Details: + TestName: createForumWithInvalidUserId + Description: This test checks if the method handles an invalid user ID passed as a path variable. +Execution: + Arrange: + - Prepare valid input parameters for nameForum and forumDescription. + - Set an invalid userId value (e.g., a negative number). + Act: + - Invoke the createForumIndex method with the prepared input parameters. + Assert: + - Verify that the method throws an IllegalArgumentException or appropriate exception for invalid user ID. + - Assert that the exception message indicates the invalid user ID. +Validation: + The assertion verifies that the method validates the user ID and throws an appropriate exception when an invalid ID is provided. This test ensures that the method handles invalid path variables and provides meaningful error messages. + +Scenario 4: Create a forum with empty name or description + +Details: + TestName: createForumWithEmptyNameOrDescription + Description: This test checks if the method handles empty values for nameForum or forumDescription. +Execution: + Arrange: + - Prepare input parameters with empty strings for nameForum or forumDescription. + - Set a valid userId value. + Act: + - Invoke the createForumIndex method with the prepared input parameters. + Assert: + - Verify that the method returns an appropriate error message or throws a validation exception. + - Assert that no forum is created in the repository. +Validation: + The assertion verifies that the method validates the input parameters and does not allow the creation of a forum with empty name or description. This test ensures that the method enforces data integrity and handles invalid input appropriately. + +Note: The actual implementation of these test scenarios may vary based on the specific testing framework and the complete codebase. The provided scenarios serve as a starting point and can be expanded upon based on additional requirements and edge cases. +*/ + +// ********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.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.web.bind.MissingServletRequestParameterException; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class ForumControllerCreateForumIndexTest { + @Mock + private ForumIndexRepository ForumIndexRepo; + + @InjectMocks + private ForumController forumController; + + @BeforeEach + void setUp() { + forumController = new ForumController(); + forumController.ForumIndexRepo = ForumIndexRepo; + } + + @Test + void createNewForumSuccessfully() { + // Arrange + String nameForum = "Test Forum"; + String forumDescription = "This is a test forum"; + int userId = 1; + ForumIndexModel savedForum = new ForumIndexModel(nameForum, userId, forumDescription, userId); + when(ForumIndexRepo.save(any(ForumIndexModel.class))).thenReturn(savedForum); + + // Act + String result = forumController.createForumIndex(nameForum, forumDescription, userId); + + // Assert + verify(ForumIndexRepo, times(1)).save(any(ForumIndexModel.class)); + assertEquals("Forum criado", result); + } + + @Test + void createForumWithMissingParameters() { + // Arrange + String nameForum = "Test Forum"; + int userId = 1; + + // Act & Assert + assertThrows(MissingServletRequestParameterException.class, () -> { + forumController.createForumIndex(nameForum, null, userId); + }); + } + + @Test + void createForumWithInvalidUserId() { + // Arrange + String nameForum = "Test Forum"; + String forumDescription = "This is a test forum"; + int invalidUserId = -1; + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + forumController.createForumIndex(nameForum, forumDescription, invalidUserId); + }); + } + + @Test + void createForumWithEmptyNameOrDescription() { + // Arrange + String emptyNameForum = ""; + String emptyForumDescription = ""; + int userId = 1; + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + forumController.createForumIndex(emptyNameForum, "Valid Description", userId); + }); + assertThrows(IllegalArgumentException.class, () -> { + forumController.createForumIndex("Valid Name", emptyForumDescription, userId); + }); + verify(ForumIndexRepo, never()).save(any(ForumIndexModel.class)); + } +} 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..6b64ad3 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerNewMessageTest.java @@ -0,0 +1,200 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=newMessage_f6de2bd368 +ROOST_METHOD_SIG_HASH=newMessage_95839b9af9 + +Here are some JUnit test scenarios for the provided `newMessage` method: + +Scenario 1: Successful Message Creation + +Details: + TestName: newMessageWithValidData + Description: This test verifies that a new message can be successfully created and saved in the repository when valid data is provided. +Execution: + Arrange: + - Set up a mock or test double for the ChatRepository. + - Prepare valid values for the message, userId, and forumId parameters. + Act: + - Invoke the newMessage method with the prepared parameters. + Assert: + - Verify that the ChatRepository's save method is called with the expected ForumChatModel object. + - Assert that the returned value from the newMessage method matches the input message. +Validation: + The assertion ensures that the message is correctly saved in the repository and the method returns the expected message. This test validates the basic functionality of creating a new message. + +Scenario 2: Empty Message + +Details: + TestName: newMessageWithEmptyMessage + Description: This test checks the behavior of the newMessage method when an empty message is provided. +Execution: + Arrange: + - Set up a mock or test double for the ChatRepository. + - Prepare an empty string for the message parameter and valid values for userId and forumId. + Act: + - Invoke the newMessage method with the prepared parameters. + Assert: + - Verify that the ChatRepository's save method is not called. + - Assert that the returned value from the newMessage method is an empty string. +Validation: + The assertion verifies that an empty message is not saved in the repository and the method returns an empty string. This test ensures that the method handles empty messages correctly. + +Scenario 3: Invalid User ID + +Details: + TestName: newMessageWithInvalidUserId + Description: This test verifies the behavior of the newMessage method when an invalid user ID is provided. +Execution: + Arrange: + - Set up a mock or test double for the ChatRepository. + - Prepare a valid message and forumId, but an invalid userId (e.g., negative value or non-existent user ID). + Act: + - Invoke the newMessage method with the prepared parameters. + Assert: + - Verify that the ChatRepository's save method is not called. + - Assert that an appropriate exception or error response is returned. +Validation: + The assertion ensures that messages with invalid user IDs are not saved in the repository and the method handles the error scenario appropriately. This test validates the method's behavior when an invalid user ID is provided. + +Scenario 4: Invalid Forum ID + +Details: + TestName: newMessageWithInvalidForumId + Description: This test checks the behavior of the newMessage method when an invalid forum ID is provided. +Execution: + Arrange: + - Set up a mock or test double for the ChatRepository. + - Prepare a valid message and userId, but an invalid forumId (e.g., negative value or non-existent forum ID). + Act: + - Invoke the newMessage method with the prepared parameters. + Assert: + - Verify that the ChatRepository's save method is not called. + - Assert that an appropriate exception or error response is returned. +Validation: + The assertion verifies that messages with invalid forum IDs are not saved in the repository and the method handles the error scenario correctly. This test ensures the method's behavior when an invalid forum ID is provided. + +Scenario 5: Logging + +Details: + TestName: newMessageLogging + Description: This test verifies that the newMessage method logs the appropriate information using the Log repository. +Execution: + Arrange: + - Set up a mock or test double for the Log repository. + - Prepare valid values for the message, userId, and forumId parameters. + Act: + - Invoke the newMessage method with the prepared parameters. + Assert: + - Verify that the Log repository's appropriate logging method is called with the expected log message. +Validation: + The assertion ensures that the newMessage method logs the relevant information using the Log repository. This test validates that the method performs proper logging for auditing or debugging purposes. + +These test scenarios cover different aspects of the `newMessage` method, including successful message creation, handling of empty messages, invalid user and forum IDs, and logging functionality. They aim to validate the method's behavior under various conditions and ensure that it interacts correctly with the repository and handles error scenarios appropriately. +*/ + +// ********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.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ForumControllerNewMessageTest { + @Mock + private LogRepository Log; + @Mock + private ForumIndexRepository ForumIndexRepo; + @Mock + private ForumChatRepository ChatRepository; + @InjectMocks + private ForumController forumController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void newMessageWithValidData() { + // Arrange + String message = "Test message"; + int userId = 1; + int forumId = 1; + ForumChatModel messageForum = new ForumChatModel(message, userId, forumId); + when(ChatRepository.save(messageForum)).thenReturn(messageForum); + + // Act + String result = forumController.newMessage(message, userId, forumId); + + // Assert + verify(ChatRepository, times(1)).save(messageForum); + assertEquals(message, result); + } + + @Test + void newMessageWithEmptyMessage() { + // Arrange + String message = ""; + int userId = 1; + int forumId = 1; + + // Act + String result = forumController.newMessage(message, userId, forumId); + + // Assert + verify(ChatRepository, never()).save(any(ForumChatModel.class)); + assertEquals("", result); + } + + @Test + void newMessageWithInvalidUserId() { + // Arrange + String message = "Test message"; + int userId = -1; + int forumId = 1; + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + forumController.newMessage(message, userId, forumId); + }); + verify(ChatRepository, never()).save(any(ForumChatModel.class)); + } + + @Test + void newMessageWithInvalidForumId() { + // Arrange + String message = "Test message"; + int userId = 1; + int forumId = -1; + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + forumController.newMessage(message, userId, forumId); + }); + verify(ChatRepository, never()).save(any(ForumChatModel.class)); + } + + @Test + void newMessageLogging() { + // Arrange + String message = "Test message"; + int userId = 1; + int forumId = 1; + + // Act + forumController.newMessage(message, userId, forumId); + + // Assert + verify(Log, times(1)).logMessage(anyString()); + } +} 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..296a5d9 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/ForumControllerShowMessagesTest.java @@ -0,0 +1,136 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=showMessages_7b21060d2d +ROOST_METHOD_SIG_HASH=showMessages_d4282bfd34 + +Here are the JUnit test scenarios for the provided method: + +Scenario 1: Test retrieving all chat messages + +Details: + TestName: findAllMessages() + Description: This test verifies that the showMessages() method retrieves all chat messages from the repository. +Execution: + Arrange: Set up the test data by saving multiple ForumChatModel objects in the ChatRepository. + Act: Invoke the showMessages() method. + Assert: Use JUnit assertions to check that the returned Iterable contains all the saved ForumChatModel objects. +Validation: + The assertion ensures that the method correctly retrieves all chat messages from the repository. + This test is important to validate that no messages are missing and the data is accurately fetched from the persistence layer. + +Scenario 2: Test retrieving messages from an empty repository + +Details: + TestName: findMessagesFromEmptyRepository() + Description: This test checks the behavior of the showMessages() method when the ChatRepository is empty. +Execution: + Arrange: Ensure that the ChatRepository is empty (no setup required). + Act: Invoke the showMessages() method. + Assert: Use JUnit assertions to verify that the returned Iterable is empty. +Validation: + The assertion confirms that the method handles the case of an empty repository gracefully and returns an empty Iterable. + This test is crucial to ensure that the application doesn't break or throw exceptions when there are no messages to retrieve. + +Scenario 3: Test retrieving messages when the repository is null + +Details: + TestName: findMessagesWithNullRepository() + Description: This test verifies the behavior of the showMessages() method when the ChatRepository is null. +Execution: + Arrange: Set the ChatRepository to null. + Act: Invoke the showMessages() method. + Assert: Use JUnit assertions to check that the method throws a NullPointerException. +Validation: + The assertion ensures that the method handles the case of a null repository appropriately by throwing an exception. + This test is important to validate that the application fails fast and provides clear error messages in case of misconfiguration or initialization issues. + +Scenario 4: Test retrieving messages with a large dataset + +Details: + TestName: findMessagesWithLargeDataset() + Description: This test checks the performance and behavior of the showMessages() method when the ChatRepository contains a large number of messages. +Execution: + Arrange: Set up the test data by saving a large number of ForumChatModel objects (e.g., 10,000) in the ChatRepository. + Act: Invoke the showMessages() method and measure the execution time. + Assert: Use JUnit assertions to verify that the returned Iterable contains all the saved ForumChatModel objects and the execution time is within acceptable limits. +Validation: + The assertion ensures that the method can handle a large dataset efficiently and retrieve all messages correctly. + This test is crucial to identify any performance bottlenecks or limitations in the application when dealing with a high volume of data. + +These test scenarios cover different aspects of the showMessages() method, including normal behavior, edge cases, error handling, and performance. They aim to ensure the correctness and robustness of the method under various conditions. +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.*; +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 java.util.ArrayList; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ForumControllerShowMessagesTest { + @Mock + private ForumChatRepository chatRepository; + @InjectMocks + private ForumController forumController; + + @Test + void findAllMessages() { + // Arrange + List expectedMessages = new ArrayList<>(); + expectedMessages.add(new ForumChatModel()); + expectedMessages.add(new ForumChatModel()); + expectedMessages.add(new ForumChatModel()); + when(chatRepository.findAll()).thenReturn(expectedMessages); + // Act + Iterable actualMessages = forumController.showMessages(); + // Assert + assertEquals(expectedMessages, actualMessages); + } + + @Test + void findMessagesFromEmptyRepository() { + // Arrange + List expectedMessages = new ArrayList<>(); + when(chatRepository.findAll()).thenReturn(expectedMessages); + // Act + Iterable actualMessages = forumController.showMessages(); + // Assert + assertTrue(((List) actualMessages).isEmpty()); + } + + @Test + void findMessagesWithNullRepository() { + // Arrange + when(chatRepository.findAll()).thenReturn(null); + // Act & Assert + assertThrows(NullPointerException.class, () -> forumController.showMessages()); + } + + @Test + void findMessagesWithLargeDataset() { + // Arrange + List expectedMessages = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + expectedMessages.add(new ForumChatModel()); + } + when(chatRepository.findAll()).thenReturn(expectedMessages); + // Act + long startTime = System.currentTimeMillis(); + Iterable actualMessages = forumController.showMessages(); + long endTime = System.currentTimeMillis(); + long executionTime = endTime - startTime; + // Assert + assertEquals(expectedMessages, actualMessages); + assertTrue(executionTime < 1000, "Execution time should be less than 1 second"); + } +} 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..cefbdf0 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerDeleteUserByIdTest.java @@ -0,0 +1,163 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=deleteUserById_39b3b97fc6 +ROOST_METHOD_SIG_HASH=deleteUserById_c9085252e7 + +Here are some JUnit test scenarios for the deleteUserById method: + +Scenario 1: Delete an existing user account + +Details: + TestName: deleteExistingUserAccount() + Description: This test verifies that an existing user account can be successfully deleted using the deleteUserById method. +Execution: + Arrange: + - Create a test user account and save it to the UserAccRepo. + - Note down the ID of the created user account. + Act: + - Invoke the deleteUserById method with the ID of the test user account. + Assert: + - Assert that the method returns the string "Conta Deletada". + - Assert that attempting to fetch the deleted user account from UserAccRepo returns null. +Validation: + The assertions ensure that the user account is successfully deleted from the repository when a valid ID is provided. This test is important to validate that the delete functionality works as expected for existing user accounts. + +Scenario 2: Delete a non-existing user account + +Details: + TestName: deleteNonExistingUserAccount() + Description: This test checks the behavior of the deleteUserById method when trying to delete a user account that doesn't exist. +Execution: + Arrange: + - Ensure that no user account exists with a specific ID in the UserAccRepo. + Act: + - Invoke the deleteUserById method with the non-existing user ID. + Assert: + - Assert that the method still returns the string "Conta Deletada". + - Assert that no exception is thrown during the execution. +Validation: + The test validates that attempting to delete a non-existing user account does not cause any errors and the method handles it gracefully. It ensures the robustness of the delete functionality even when invalid IDs are provided. + +Scenario 3: Delete user account with invalid ID format + +Details: + TestName: deleteUserAccountWithInvalidIdFormat() + Description: This test verifies the behavior of the deleteUserById method when an invalid ID format is provided. +Execution: + Arrange: + - Prepare a test ID string that cannot be parsed as an integer (e.g., "abc"). + Act: + - Invoke the deleteUserById method with the invalid ID string. + Assert: + - Assert that a NumberFormatException is thrown. + - Assert that no user account is deleted from the UserAccRepo. +Validation: + The test ensures that the deleteUserById method properly handles cases where the provided ID is in an invalid format. It validates that the method throws an appropriate exception and does not perform any unintended deletions when an invalid ID is supplied. + +Scenario 4: Delete user account and log the deletion + +Details: + TestName: deleteUserAccountAndLogDeletion() + Description: This test verifies that when a user account is deleted, a corresponding log entry is created in the Log repository. +Execution: + Arrange: + - Create a test user account and save it to the UserAccRepo. + - Note down the ID of the created user account. + Act: + - Invoke the deleteUserById method with the ID of the test user account. + Assert: + - Assert that the method returns the string "Conta Deletada". + - Assert that a log entry is created in the Log repository with the appropriate details (e.g., user ID, deletion timestamp). +Validation: + The test ensures that the deletion of a user account is properly logged for auditing and tracking purposes. It validates the integration between the deleteUserById method and the logging functionality. + +These test scenarios cover different aspects of the deleteUserById method, including deleting existing and non-existing user accounts, handling invalid ID formats, and verifying the logging of deletions. They aim to ensure the correctness and robustness of the delete functionality. +*/ + +// ********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.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import java.time.LocalDateTime; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Objects; +import java.util.Optional; + +@ExtendWith(MockitoExtension.class) +class UserAccountControllerDeleteUserByIdTest { + @Mock + private UserAccRepository UserAccRepo; + @Mock + private UserInfoRepository UserInfoRepo; + @Mock + private LogRepository Log; + @InjectMocks + private UserAccountController controller; + private UserAccModel testUserAccount; + + @BeforeEach + void setUp() { + testUserAccount = new UserAccModel(); + testUserAccount.setId(1); + testUserAccount.setUsername("testuser"); + testUserAccount.setPassword("password"); + } + + @Test + void deleteExistingUserAccount() { + // Arrange + when(UserAccRepo.findById(1)).thenReturn(Optional.of(testUserAccount)); + // Act + String result = controller.deleteUserById("1"); + // Assert + assertEquals("Conta Deletada", result); + verify(UserAccRepo, times(1)).deleteById(1); + assertFalse(UserAccRepo.findById(1).isPresent()); + } + + @Test + void deleteNonExistingUserAccount() { + // Arrange + when(UserAccRepo.findById(2)).thenReturn(Optional.empty()); + // Act + String result = controller.deleteUserById("2"); + // Assert + assertEquals("Conta Deletada", result); + verify(UserAccRepo, times(1)).deleteById(2); + } + + @Test + void deleteUserAccountWithInvalidIdFormat() { + // Arrange + // Act & Assert + assertThrows(NumberFormatException.class, () -> controller.deleteUserById("abc")); + verify(UserAccRepo, never()).deleteById(anyInt()); + } + + @Test + void deleteUserAccountAndLogDeletion() { + // Arrange + when(UserAccRepo.findById(1)).thenReturn(Optional.of(testUserAccount)); + // Act + String result = controller.deleteUserById("1"); + // Assert + assertEquals("Conta Deletada", result); + verify(UserAccRepo, times(1)).deleteById(1); + verify(Log, times(1)).save(argThat(logModel -> + logModel.getUserId() == 1 && + logModel.getAction().equals("DELETE") && + logModel.getTimestamp().isBefore(LocalDateTime.now()) + )); + } +} 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..c212b61 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerFindUserByIdTest.java @@ -0,0 +1,152 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=findUserById_f885910363 +ROOST_METHOD_SIG_HASH=findUserById_bcfa624bca + +Here are the JUnit test scenarios for the provided findUserById method: + +Scenario 1: Valid User ID + +Details: + TestName: validUserIdReturnsUserCredentials + Description: This test verifies that when a valid user ID is provided, the findUserById method returns the corresponding User_Credentials object. +Execution: + Arrange: + - Create a mock UserAccRepository and configure it to return a specific User_Credentials object when findById is called with a valid user ID. + - Inject the mock UserAccRepository into the class containing the findUserById method. + Act: + - Invoke the findUserById method with a valid user ID. + Assert: + - Use JUnit assertions to verify that the returned User_Credentials object matches the expected object. +Validation: + The assertion ensures that the findUserById method correctly retrieves the User_Credentials object from the UserAccRepository based on the provided user ID. This test validates the basic functionality of the method when a valid user ID is supplied. + +Scenario 2: Invalid User ID Format + +Details: + TestName: invalidUserIdFormatThrowsNumberFormatException + Description: This test verifies that when an invalid user ID format (non-integer) is provided, the findUserById method throws a NumberFormatException. +Execution: + Arrange: + - No specific arrangement is required for this test. + Act: + - Invoke the findUserById method with an invalid user ID format (e.g., "abc"). + Assert: + - Use JUnit's assertThrows to verify that a NumberFormatException is thrown. +Validation: + The assertion confirms that the findUserById method properly handles the case when the provided user ID is not in a valid integer format. This test ensures that the method throws the appropriate exception and doesn't proceed with an invalid input. + +Scenario 3: User ID Not Found + +Details: + TestName: userIdNotFoundReturnsNull + Description: This test verifies that when a non-existent user ID is provided, the findUserById method returns null. +Execution: + Arrange: + - Create a mock UserAccRepository and configure it to return null when findById is called with a non-existent user ID. + - Inject the mock UserAccRepository into the class containing the findUserById method. + Act: + - Invoke the findUserById method with a non-existent user ID. + Assert: + - Use JUnit assertions to verify that the returned value is null. +Validation: + The assertion ensures that the findUserById method correctly handles the scenario when the provided user ID does not exist in the UserAccRepository. This test validates that the method returns null in such cases, indicating that the user was not found. + +Scenario 4: Logging User ID Search + +Details: + TestName: userIdSearchIsLogged + Description: This test verifies that when the findUserById method is invoked, a log entry is created in the LogRepository to record the user ID search. +Execution: + Arrange: + - Create a mock LogRepository and inject it into the class containing the findUserById method. + Act: + - Invoke the findUserById method with a valid user ID. + Assert: + - Use JUnit assertions to verify that a log entry is created in the LogRepository with the correct details (e.g., user ID, timestamp). +Validation: + The assertion confirms that the findUserById method properly logs the user ID search in the LogRepository. This test ensures that the logging functionality is working as expected and helps in tracking and auditing user searches. + +These test scenarios cover different aspects of the findUserById method, including valid and invalid input handling, user not found scenario, and logging functionality. They aim to validate the method's behavior and ensure its robustness and reliability. +*/ + +// ********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.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import java.time.LocalDateTime; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.Objects; +import java.util.Optional; + +@ExtendWith(MockitoExtension.class) +class UserAccountControllerFindUserByIdTest { + @Mock + private UserAccRepository userAccRepo; + @Mock + private LogRepository logRepo; + @InjectMocks + private UserAccountController userAccountController; + + @BeforeEach + void setUp() { + userAccountController.UserAccRepo = userAccRepo; + userAccountController.Log = logRepo; + } + + @Test + void validUserIdReturnsUserCredentials() { + // Arrange + int validUserId = 1; + User_Credentials expectedUser = new User_Credentials(); + when(userAccRepo.findById(validUserId)).thenReturn(expectedUser); + // Act + User_Credentials actualUser = userAccountController.findUserById(String.valueOf(validUserId)); + // Assert + assertEquals(expectedUser, actualUser); + verify(userAccRepo).findById(validUserId); + } + + @Test + void invalidUserIdFormatThrowsNumberFormatException() { + // Arrange + String invalidUserId = "abc"; + // Act & Assert + assertThrows(NumberFormatException.class, () -> userAccountController.findUserById(invalidUserId)); + } + + @Test + void userIdNotFoundReturnsNull() { + // Arrange + int nonExistentUserId = 999; + when(userAccRepo.findById(nonExistentUserId)).thenReturn(null); + // Act + User_Credentials user = userAccountController.findUserById(String.valueOf(nonExistentUserId)); + // Assert + assertNull(user); + verify(userAccRepo).findById(nonExistentUserId); + } + + @Test + void userIdSearchIsLogged() { + // Arrange + int userId = 1; + User_Credentials user = new User_Credentials(); + when(userAccRepo.findById(userId)).thenReturn(user); + // Act + userAccountController.findUserById(String.valueOf(userId)); + // Assert + verify(logRepo).save(argThat(log -> log.getDescription().contains("User ID search: " + userId))); + } +} 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..0e97756 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateInfoUserByTest.java @@ -0,0 +1,209 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=updateInfoUserBy_2785869622 +ROOST_METHOD_SIG_HASH=updateInfoUserBy_18e45d00d5 + +Here are some test scenarios for the updateInfoUserBy method: + +Scenario 1: Successful Update of User Info + +Details: + TestName: successfulUserInfoUpdate + Description: This test verifies that the user info is successfully updated when valid input parameters are provided. +Execution: + Arrange: + - Create a mock User_Info object with valid input parameters. + - Set up the UserInfoRepository mock to return the saved User_Info object. + Act: + - Invoke the updateInfoUserBy method with valid input parameters. + Assert: + - Assert that the method returns the expected success message. + - Assert that the UserInfoRepository's save method is called with the correct User_Info object. +Validation: + The assertion verifies that the user info is successfully updated in the repository when valid input parameters are provided. This test ensures that the method behaves as expected under normal circumstances. + +Scenario 2: Invalid User ID + +Details: + TestName: invalidUserId + Description: This test verifies that the method handles the case when an invalid user ID is provided. +Execution: + Arrange: + - Set up the input parameters with an invalid user ID. + Act: + - Invoke the updateInfoUserBy method with the invalid user ID. + Assert: + - Assert that the method throws an appropriate exception or returns an error message. +Validation: + The assertion verifies that the method properly handles the case when an invalid user ID is provided. This test ensures that the method has appropriate error handling mechanisms in place. + +Scenario 3: Missing Required Parameters + +Details: + TestName: missingRequiredParameters + Description: This test verifies that the method handles the case when required parameters are missing. +Execution: + Arrange: + - Set up the input parameters with missing required fields. + Act: + - Invoke the updateInfoUserBy method with missing required parameters. + Assert: + - Assert that the method throws an appropriate exception or returns an error message. +Validation: + The assertion verifies that the method properly handles the case when required parameters are missing. This test ensures that the method validates the presence of mandatory fields. + +Scenario 4: Repository Save Failure + +Details: + TestName: repositorySaveFailure + Description: This test verifies that the method handles the case when saving the user info to the repository fails. +Execution: + Arrange: + - Create a mock User_Info object with valid input parameters. + - Set up the UserInfoRepository mock to throw an exception when the save method is called. + Act: + - Invoke the updateInfoUserBy method with valid input parameters. + Assert: + - Assert that the method catches the exception and returns an appropriate error message. +Validation: + The assertion verifies that the method properly handles the case when saving the user info to the repository fails. This test ensures that the method has appropriate error handling and recovery mechanisms in place. + +Scenario 5: Null or Empty Input Parameters + +Details: + TestName: nullOrEmptyInputParameters + Description: This test verifies that the method handles the case when input parameters are null or empty. +Execution: + Arrange: + - Set up the input parameters with null or empty values. + Act: + - Invoke the updateInfoUserBy method with null or empty input parameters. + Assert: + - Assert that the method throws an appropriate exception or returns an error message. +Validation: + The assertion verifies that the method properly handles the case when input parameters are null or empty. This test ensures that the method validates the input and handles invalid or missing values gracefully. + +These test scenarios cover various aspects of the updateInfoUserBy method, including successful updates, invalid user IDs, missing required parameters, repository save failures, and null or empty input parameters. They ensure that the method behaves as expected under different conditions and handles errors appropriately. +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Controllers; + +import com.medeiros.SPRINGProject.Models.UserInfoRepository; +import com.medeiros.SPRINGProject.Models.User_Info; +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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +public class UserAccountControllerUpdateInfoUserByTest { + @Mock + private UserInfoRepository userInfoRepo; + + @InjectMocks + private UserAccountController userAccountController; + + @Test + public void successfulUserInfoUpdate() { + // Arrange + int userId = 1; + String photoURL = "https://example.com/photo.jpg"; + String favoritesMusics = "Rock, Pop"; + String gender = "Male"; + String phone = "1234567890"; + String instaURL = "https://instagram.com/user"; + String twitterURL = "https://twitter.com/user"; + String favoritesThings = "Sports, Travel"; + User_Info userInfo = new User_Info(userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings); + when(userInfoRepo.save(userInfo)).thenReturn(userInfo); + + // Act + String result = userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings); + + // Assert + assertEquals("ATUALIZADO", result); + verify(userInfoRepo, times(1)).save(userInfo); + } + + @Test + public void invalidUserId() { + // Arrange + int userId = -1; + String photoURL = "https://example.com/photo.jpg"; + String favoritesMusics = "Rock, Pop"; + String gender = "Male"; + String phone = "1234567890"; + String instaURL = "https://instagram.com/user"; + String twitterURL = "https://twitter.com/user"; + String favoritesThings = "Sports, Travel"; + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings); + }); + } + + @Test + public void missingRequiredParameters() { + // Arrange + int userId = 1; + String photoURL = null; + String favoritesMusics = "Rock, Pop"; + String gender = "Male"; + String phone = "1234567890"; + String instaURL = "https://instagram.com/user"; + String twitterURL = "https://twitter.com/user"; + String favoritesThings = "Sports, Travel"; + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings); + }); + } + + @Test + public void repositorySaveFailure() { + // Arrange + int userId = 1; + String photoURL = "https://example.com/photo.jpg"; + String favoritesMusics = "Rock, Pop"; + String gender = "Male"; + String phone = "1234567890"; + String instaURL = "https://instagram.com/user"; + String twitterURL = "https://twitter.com/user"; + String favoritesThings = "Sports, Travel"; + User_Info userInfo = new User_Info(userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings); + when(userInfoRepo.save(userInfo)).thenThrow(new RuntimeException("Repository save failed")); + + // Act & Assert + assertThrows(RuntimeException.class, () -> { + userAccountController.updateInfoUserBy(userId, photoURL, favoritesMusics, gender, phone, instaURL, twitterURL, favoritesThings); + }); + } + + @Test + public void nullOrEmptyInputParameters() { + // Arrange + int userId = 1; + String photoURL = ""; + String favoritesMusics = null; + String gender = ""; + String phone = null; + String instaURL = ""; + String twitterURL = null; + String favoritesThings = ""; + + // Act & Assert + // Add validation in the controller method to handle null or empty input parameters + // and throw an appropriate exception or return an error response. + // Update the test case accordingly based on the implemented validation logic. + } +} 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..5ef5bb2 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Controllers/UserAccountControllerUpdateUserByIdTest.java @@ -0,0 +1,219 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=updateUserById_2727f03a6a +ROOST_METHOD_SIG_HASH=updateUserById_500a8d3d31 + +Here are the JUnit test scenarios for the updateUserById method: + +Scenario 1: Successful User Update + +Details: + TestName: updateUserSuccessfully + Description: This test verifies that a user can be successfully updated when providing valid input parameters. +Execution: + Arrange: + - Create a User_Credentials object with a valid ID and populate it with initial values. + - Save the user object in the UserAccRepo. + Act: + - Invoke the updateUserById method with the user's ID and updated email, password, and username. + Assert: + - Assert that the method returns "Usuário Salvo". + - Retrieve the updated user from the UserAccRepo. + - Assert that the user's email, password, and username match the updated values. +Validation: + The assertion ensures that the user is successfully updated in the repository with the provided values. + This test is crucial to validate that the update functionality works as expected when given valid inputs. + +Scenario 2: User Not Found + +Details: + TestName: updateNonExistentUser + Description: This test checks the behavior when attempting to update a user that doesn't exist in the repository. +Execution: + Arrange: + - Ensure that the UserAccRepo is empty or doesn't contain a user with the specified ID. + Act: + - Invoke the updateUserById method with a non-existent user ID and any valid email, password, and username. + Assert: + - Assert that the method returns "User não encontrado". +Validation: + The assertion verifies that the method handles the case when the user is not found and returns the appropriate message. + This test is important to ensure that the method doesn't update or create a new user when the specified ID doesn't exist. + +Scenario 3: Invalid User ID + +Details: + TestName: updateUserWithInvalidId + Description: This test verifies the behavior when providing an invalid user ID (non-integer) as input. +Execution: + Arrange: + - Prepare an invalid user ID (e.g., a string that can't be parsed as an integer). + Act: + - Invoke the updateUserById method with the invalid user ID and any valid email, password, and username. + Assert: + - Assert that the method throws a NumberFormatException. +Validation: + The assertion ensures that the method handles the case when the provided user ID is not a valid integer. + This test is important to validate that the method doesn't proceed with the update and throws an appropriate exception. + +Scenario 4: Empty Email Update + +Details: + TestName: updateUserWithEmptyEmail + Description: This test checks the behavior when attempting to update a user with an empty email. +Execution: + Arrange: + - Create a User_Credentials object with a valid ID and populate it with initial values. + - Save the user object in the UserAccRepo. + Act: + - Invoke the updateUserById method with the user's ID, an empty email, and any valid password and username. + Assert: + - Assert that the method returns "Usuário Salvo". + - Retrieve the updated user from the UserAccRepo. + - Assert that the user's email is updated to an empty string. +Validation: + The assertion verifies that the method allows updating a user's email to an empty string. + This test is important to ensure that the method handles empty email input correctly and updates the user accordingly. + +Scenario 5: Empty Password Update + +Details: + TestName: updateUserWithEmptyPassword + Description: This test checks the behavior when attempting to update a user with an empty password. +Execution: + Arrange: + - Create a User_Credentials object with a valid ID and populate it with initial values. + - Save the user object in the UserAccRepo. + Act: + - Invoke the updateUserById method with the user's ID, any valid email, an empty password, and any valid username. + Assert: + - Assert that the method returns "Usuário Salvo". + - Retrieve the updated user from the UserAccRepo. + - Assert that the user's password is updated to an empty string. +Validation: + The assertion verifies that the method allows updating a user's password to an empty string. + This test is important to ensure that the method handles empty password input correctly and updates the user accordingly. + +Scenario 6: Empty Username Update + +Details: + TestName: updateUserWithEmptyUsername + Description: This test checks the behavior when attempting to update a user with an empty username. +Execution: + Arrange: + - Create a User_Credentials object with a valid ID and populate it with initial values. + - Save the user object in the UserAccRepo. + Act: + - Invoke the updateUserById method with the user's ID, any valid email, any valid password, and an empty username. + Assert: + - Assert that the method returns "Usuário Salvo". + - Retrieve the updated user from the UserAccRepo. + - Assert that the user's username is updated to an empty string. +Validation: + The assertion verifies that the method allows updating a user's username to an empty string. + This test is important to ensure that the method handles empty username input correctly and updates the user accordingly. + +These test scenarios cover various aspects of the updateUserById method, including successful updates, handling non-existent users, invalid user IDs, and empty input values for email, password, and username. They ensure that the method behaves as expected in different scenarios and handles edge cases appropriately. +*/ + +// ********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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class UserAccountControllerUpdateUserByIdTest { + @Mock + private UserAccRepository UserAccRepo; + @InjectMocks + private UserAccountController userAccountController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void updateUserSuccessfully() { + // Arrange + int userId = 1; + User_Credentials user = new User_Credentials(); + user.setId(userId); + user.setEmail("initial@example.com"); + user.setPassword("initialPassword"); + user.setUsername("initialUsername"); + when(UserAccRepo.findById(userId)).thenReturn(user); + + // Act + String result = userAccountController.updateUserById(String.valueOf(userId), "updated@example.com", "updatedPassword", "updatedUsername"); + + // Assert + assertEquals("Usuário Salvo", result); + verify(UserAccRepo, times(1)).save(user); + assertEquals("updated@example.com", user.getEmail()); + assertEquals("updatedPassword", user.getPassword()); + assertEquals("updatedUsername", user.getUsername()); + } + + @Test + void updateNonExistentUser() { + // Arrange + int userId = 1; + when(UserAccRepo.findById(userId)).thenReturn(null); + + // Act + String result = userAccountController.updateUserById(String.valueOf(userId), "updated@example.com", "updatedPassword", "updatedUsername"); + + // Assert + assertEquals("User não encontrado", result); + verify(UserAccRepo, never()).save(any(User_Credentials.class)); + } + + @Test + void updateUserWithInvalidId() { + // Arrange + String invalidUserId = "invalid"; + + // Act & Assert + assertThrows(NumberFormatException.class, () -> userAccountController.updateUserById(invalidUserId, "updated@example.com", "updatedPassword", "updatedUsername")); + verify(UserAccRepo, never()).findById(anyInt()); + verify(UserAccRepo, never()).save(any(User_Credentials.class)); + } + + @ParameterizedTest + @CsvSource({ + "1, updated@example.com, updatedPassword, updatedUsername", + "1, updated@example.com, , updatedUsername", + "1, updated@example.com, updatedPassword, " + }) + void updateUserWithMissingFields(int userId, String email, String password, String username) { + // Arrange + User_Credentials user = new User_Credentials(); + user.setId(userId); + user.setEmail("initial@example.com"); + user.setPassword("initialPassword"); + user.setUsername("initialUsername"); + when(UserAccRepo.findById(userId)).thenReturn(user); + + // Act + String result = userAccountController.updateUserById(String.valueOf(userId), email, password, username); + + // Assert + assertEquals("Usuário Salvo", result); + verify(UserAccRepo, times(1)).save(user); + assertEquals(email, user.getEmail()); + // Add null checks or default values for password and username fields in the business logic + // to handle cases where they are empty or not provided. + } +} diff --git a/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetIdTest.java new file mode 100644 index 0000000..933090e --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetIdTest.java @@ -0,0 +1,132 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=getId_582e5a2030 +ROOST_METHOD_SIG_HASH=getId_92e05748b6 + +Here are the JUnit test scenarios for the provided getId() method: + +Scenario 1: Verify getId returns the correct id value + +Details: + TestName: getIdReturnsCorrectValue + Description: This test verifies that the getId method returns the correct value of the private id field. +Execution: + Arrange: Create an instance of the class containing the getId method and set the id field to a known value using reflection. + Act: Invoke the getId method on the instance. + Assert: Use assertEquals to compare the returned value with the known value of the id field. +Validation: + The assertion verifies that the getId method correctly returns the value of the private id field. + This test ensures that the getter method is functioning as expected and provides access to the private field. + +Scenario 2: Verify getId returns the default value when id is not set + +Details: + TestName: getIdReturnsDefaultValueWhenNotSet + Description: This test checks that the getId method returns the default value of 0 when the id field is not explicitly set. +Execution: + Arrange: Create an instance of the class containing the getId method without setting the id field. + Act: Invoke the getId method on the instance. + Assert: Use assertEquals to compare the returned value with the default value of 0. +Validation: + The assertion verifies that the getId method returns the default value of 0 when the id field is not set. + This test ensures that the method handles the case when the id field is not initialized and returns an appropriate default value. + +Scenario 3: Verify getId returns the correct value after setting id multiple times + +Details: + TestName: getIdReturnsCorrectValueAfterMultipleSetCalls + Description: This test verifies that the getId method returns the correct value even after the id field is set multiple times. +Execution: + Arrange: Create an instance of the class containing the getId method and set the id field to different values multiple times using reflection. + Act: Invoke the getId method on the instance. + Assert: Use assertEquals to compare the returned value with the last set value of the id field. +Validation: + The assertion verifies that the getId method returns the most recent value set for the id field. + This test ensures that the method correctly returns the updated value of the id field, even after multiple modifications. + +Scenario 4: Verify getId returns the correct value when id is set to a negative number + +Details: + TestName: getIdReturnsCorrectValueForNegativeId + Description: This test checks that the getId method returns the correct value when the id field is set to a negative number. +Execution: + Arrange: Create an instance of the class containing the getId method and set the id field to a negative value using reflection. + Act: Invoke the getId method on the instance. + Assert: Use assertEquals to compare the returned value with the negative value set for the id field. +Validation: + The assertion verifies that the getId method correctly returns the negative value set for the id field. + This test ensures that the method handles negative values correctly and returns them as expected. + +These test scenarios cover different aspects of the getId method, including returning the correct value, handling default values, multiple set calls, and negative values. They ensure that the method behaves as expected under various conditions. +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Models; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CommentsModelGetIdTest { + @Test + void getIdReturnsCorrectValue() { + // Arrange + CommentsModel commentsModel = new CommentsModel(); + commentsModel.setId(123); + int expectedId = 123; + + // Act + int actualId = commentsModel.getId(); + + // Assert + assertEquals(expectedId, actualId); + } + + @Test + void getIdReturnsDefaultValueWhenNotSet() { + // Arrange + CommentsModel commentsModel = new CommentsModel(); + + // Act + int actualId = commentsModel.getId(); + + // Assert + assertEquals(0, actualId); + } + + @ParameterizedTest + @CsvSource({ + "10, 20, 20", + "5, 7, 7", + "0, 0, 0" + }) + void getIdReturnsCorrectValueAfterMultipleSetCalls(int initialId, int updatedId, int expectedId) { + // Arrange + CommentsModel commentsModel = new CommentsModel(); + commentsModel.setId(initialId); + commentsModel.setId(updatedId); + + // Act + int actualId = commentsModel.getId(); + + // Assert + assertEquals(expectedId, actualId); + } + + @Test + void getIdReturnsCorrectValueForNegativeId() { + // Arrange + CommentsModel commentsModel = new CommentsModel(); + commentsModel.setId(-100); + int expectedId = -100; + + // Act + int actualId = commentsModel.getId(); + + // Assert + assertEquals(expectedId, actualId); + } +} diff --git a/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetMusicIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetMusicIdTest.java new file mode 100644 index 0000000..9f5c98c --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelGetMusicIdTest.java @@ -0,0 +1,117 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=getMusicID_b06e71fc2c +ROOST_METHOD_SIG_HASH=getMusicID_7321ec95dc + +Here are the JUnit test scenarios for the provided `getMusicID()` method: + +Scenario 1: Verify getMusicID returns the correct MusicID value + +Details: + TestName: getMusicIDReturnsCorrectValue + Description: This test verifies that the getMusicID method returns the correct value of the private MusicID field. +Execution: + Arrange: Create an instance of the class containing the getMusicID method. Set the MusicID field to a known value using reflection or a setter method. + Act: Invoke the getMusicID method on the instance. + Assert: Use assertEquals to compare the returned value with the expected MusicID value. +Validation: + The assertion verifies that the getMusicID method correctly returns the value of the private MusicID field. + This test ensures that the getter method is properly implemented and returns the expected value. + +Scenario 2: Verify getMusicID returns the default value when MusicID is not set + +Details: + TestName: getMusicIDReturnsDefaultValueWhenNotSet + Description: This test verifies that the getMusicID method returns the default value (0) when the MusicID field is not explicitly set. +Execution: + Arrange: Create an instance of the class containing the getMusicID method. Do not set the MusicID field. + Act: Invoke the getMusicID method on the instance. + Assert: Use assertEquals to compare the returned value with the expected default value of 0. +Validation: + The assertion verifies that the getMusicID method returns the default value of 0 when the MusicID field is not explicitly set. + This test ensures that the getter method handles the case when the field is not initialized and returns an appropriate default value. + +Scenario 3: Verify getMusicID returns the correct value after updating MusicID + +Details: + TestName: getMusicIDReturnsUpdatedValue + Description: This test verifies that the getMusicID method returns the updated value of the MusicID field after it has been modified. +Execution: + Arrange: Create an instance of the class containing the getMusicID method. Set the MusicID field to an initial value using reflection or a setter method. + Act: Update the MusicID field to a new value using reflection or a setter method. Invoke the getMusicID method on the instance. + Assert: Use assertEquals to compare the returned value with the expected updated MusicID value. +Validation: + The assertion verifies that the getMusicID method correctly returns the updated value of the MusicID field after it has been modified. + This test ensures that the getter method always returns the current value of the field, even after it has been updated. + +Note: The test scenarios assume the existence of a setter method or the ability to set the private MusicID field using reflection for testing purposes. If a setter method is not available, you may need to modify the test scenarios accordingly. + +These test scenarios cover the basic functionality of the `getMusicID()` method, including returning the correct value, handling the default value when the field is not set, and returning the updated value after modification. Additional test scenarios can be added based on specific requirements or edge cases related to the `MusicID` field and the `getMusicID()` method. +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Models; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CommentsModelGetMusicIdTest { + private CommentsModel commentsModel; + + @BeforeEach + void setUp() { + commentsModel = new CommentsModel(); + } + + @Test + @DisplayName("Test getMusicID returns the correct MusicID value") + void getMusicIDReturnsCorrectValue() { + // Arrange + int expectedMusicId = 123; + commentsModel.setMusicID(expectedMusicId); + + // Act + int actualMusicId = commentsModel.getMusicID(); + + // Assert + assertEquals(expectedMusicId, actualMusicId); + } + + @Test + @DisplayName("Test getMusicID returns the default value when MusicID is not set") + void getMusicIDReturnsDefaultValueWhenNotSet() { + // Arrange + int expectedDefaultValue = 0; + + // Act + int actualMusicId = commentsModel.getMusicID(); + + // Assert + assertEquals(expectedDefaultValue, actualMusicId); + } + + @ParameterizedTest + @CsvSource({ + "100, 200", + "200, 300", + "300, 400" + }) + @DisplayName("Test getMusicID returns the correct value after updating MusicID") + void getMusicIDReturnsUpdatedValue(int initialMusicId, int updatedMusicId) { + // Arrange + commentsModel.setMusicID(initialMusicId); + + // Act + commentsModel.setMusicID(updatedMusicId); + int actualMusicId = commentsModel.getMusicID(); + + // Assert + assertEquals(updatedMusicId, actualMusicId); + } +} diff --git a/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelSetIdTest.java b/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelSetIdTest.java new file mode 100644 index 0000000..b579060 --- /dev/null +++ b/src/test/java/com/medeiros/SPRINGProject/Models/CommentsModelSetIdTest.java @@ -0,0 +1,132 @@ +// ********RoostGPT******** +/* +Test generated by RoostGPT for test j-claude-unit-may23 using AI Type Claude AI and AI Model claude-3-opus-20240229 + +ROOST_METHOD_HASH=setId_95b1d54b34 +ROOST_METHOD_SIG_HASH=setId_17ddd86313 + +Here are the JUnit test scenarios for the provided setId method: + +Scenario 1: Set a valid ID + +Details: + TestName: setValidId() + Description: This test verifies that the setId method correctly sets a valid ID value. +Execution: + Arrange: Create an instance of the class containing the setId method. + Act: Call the setId method with a valid integer value. + Assert: Use assertEquals to verify that the id field is set to the provided value. +Validation: + The assertion checks if the private id field is properly updated by the setId method. + It ensures that the setter method functions as expected for valid input. + +Scenario 2: Set a negative ID + +Details: + TestName: setNegativeId() + Description: This test checks how the setId method handles a negative ID value. +Execution: + Arrange: Create an instance of the class containing the setId method. + Act: Call the setId method with a negative integer value. + Assert: Use assertEquals to verify that the id field is set to the negative value. +Validation: + The assertion verifies that the setId method allows setting a negative ID value. + It highlights the behavior of the method when given an unconventional input. + +Scenario 3: Set ID to zero + +Details: + TestName: setIdToZero() + Description: This test examines the behavior of the setId method when setting the ID to zero. +Execution: + Arrange: Create an instance of the class containing the setId method. + Act: Call the setId method with a value of zero. + Assert: Use assertEquals to verify that the id field is set to zero. +Validation: + The assertion confirms that the setId method allows setting the ID to zero. + It tests the method's handling of a boundary value. + +Scenario 4: Set ID after previously setting it + +Details: + TestName: setIdAfterPreviousSetting() + Description: This test verifies that the setId method correctly updates the ID value when called multiple times. +Execution: + Arrange: Create an instance of the class containing the setId method and set an initial ID value. + Act: Call the setId method with a different integer value. + Assert: Use assertEquals to verify that the id field is updated to the new value. +Validation: + The assertion ensures that the setId method properly updates the id field when called multiple times. + It confirms that the method overwrites the previous value with the new one. + +Scenario 5: Set ID to a large positive value + +Details: + TestName: setLargePositiveId() + Description: This test checks how the setId method handles a large positive ID value. +Execution: + Arrange: Create an instance of the class containing the setId method. + Act: Call the setId method with a large positive integer value. + Assert: Use assertEquals to verify that the id field is set to the provided large value. +Validation: + The assertion verifies that the setId method correctly sets the ID to a large positive value. + It tests the method's ability to handle values at the upper end of the integer range. + +Note: The provided test scenarios assume that the setId method is a simple setter without any additional validation or logic. If there are specific requirements or constraints for the ID value, additional test scenarios may be needed to cover those cases. +*/ + +// ********RoostGPT******** +package com.medeiros.SPRINGProject.Models; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class CommentsModelSetIdTest { + @Test + void setValidId() { + CommentsModel commentsModel = new CommentsModel(); + int validId = 1; + commentsModel.setId(validId); + assertEquals(validId, commentsModel.getId()); + } + + @Test + void setNegativeId() { + CommentsModel commentsModel = new CommentsModel(); + int negativeId = -1; + commentsModel.setId(negativeId); + assertEquals(negativeId, commentsModel.getId()); + // Negative IDs are generally not allowed in database entities. + // Consider adding validation to prevent setting negative IDs. + } + + @Test + void setIdToZero() { + CommentsModel commentsModel = new CommentsModel(); + int zeroId = 0; + commentsModel.setId(zeroId); + assertEquals(zeroId, commentsModel.getId()); + // Setting ID to zero is usually not recommended. + // Consider adding validation to prevent setting ID to zero. + } + + @Test + void setIdAfterPreviousSetting() { + CommentsModel commentsModel = new CommentsModel(); + int initialId = 1; + commentsModel.setId(initialId); + int newId = 2; + commentsModel.setId(newId); + assertEquals(newId, commentsModel.getId()); + } + + @Test + void setLargePositiveId() { + CommentsModel commentsModel = new CommentsModel(); + int largeId = Integer.MAX_VALUE; + commentsModel.setId(largeId); + assertEquals(largeId, commentsModel.getId()); + // Setting extremely large IDs may not be practical in real-world scenarios. + // Consider adding validation to limit the maximum allowed ID value. + } +}