Creating a Get Query for an Entity

For the past few weeks, I’ve been learning and expanding my knowledge of the CQRS pattern. Under the guidance of Mr. Peter, I have been steadily progressing in my understanding of CQRS. This week, my focus was on implementing the final components of the pattern: the “Get by Id” and “Get List” functionalities for an entity.

First, I created the Get List Query Handler class. This class implements the IRequestHandler interface and is responsible for handling the query to retrieve a list of entities. It utilizes the IMapper and a specific service interface. Then, within the Handle method, I first check if the search name provided in the query is null and assign an empty string if necessary. This allows for more flexible search functionality. Next, I call a service to read the paged entity based on the search criteria and pagination details provided in the query.

To prepare the response, I use AutoMapper to map the retrieved list of entities to a list of the entity Dto objects. Additionally, I fetch the total count of entities that match the search criteria to assist with pagination. Finally, I return a PagedDto object containing the count, the mapped list, and the page and size information from the query. 

Moving on to the Get Query By Id Handler class, which handles the query to retrieve a specific entity by its ID. Similar to the previous handler, it implements the IRequestHandler interface and relies on the IMapper and service interfaces. Inside the Handle method, I perform validation using the Get Query Validator. If any validation errors occur, I throw an InvalidOperationException with the corresponding error messages. Otherwise, I proceed to retrieve the entity using the service based on the supplied Id in the query. If an entity is found, I map it to the Dto using AutoMapper and return the result. However, if the entity is not found, I return null to indicate that no entity with the specified ID exists.

To ensure the correctness of my implementation, I have also included a couple of unit tests. These tests verify the success scenarios for both the Read By Id and Read List methods. They utilize a client to simulate HTTP requests and check the returned status codes and data.

In addition to the query handlers and tests, I have also expanded my knowledge by implementing another implementation of the service interface. This interface serves as the abstraction for fetching entities based on various criteria, and I made sure to create the methods in asynchronous form as advised by Mr Peter.

The added methods in the service interface provide the flexibility to retrieve entities by ID, search name, and pagination. For example, the ReadByIdAsync method accepts an ID as a parameter and fetches the corresponding entity asynchronously. It utilizes the underlying data access layer, to retrieve the entity. Similarly, the ReadPagedByAsync method takes parameters such as a search name, page number, and page size to perform a paged retrieval of entities based on the search criteria.

Overall, by implementing these methods in an asynchronous manner, I ensure that the retrieval operations can be performed efficiently and non-blocking. This enables better scalability and responsiveness in the application, especially when dealing with a large number of entities or concurrent requests. Moving forward, my next task involves delving into the UI aspect, where I will embark on learning about WPF, MVVM, and Prism.

Exploring Testing

Hi there, hope you have a nice day. For the past week, I have been working on doing some changes for my test case. Focusing on do a little changes and add some new methods to make the test case passed without errors.

First and foremost, during last week I been doing some changes in the test case. I learned a lot of new things, methods and also a function. For example, the difference between mockClear and mockReset. MockClear does and also removes any mocked return values or implementations. Often this is useful when you want to clean up a mock usage data between two assertions. Beware that this method will replace the function, not just calls and also instances. You should therefore avoid assigning to other variables, temporary or not, to make sure it do not access stale data. Meanwhile, mockReset will reset all information stored in the mock, including any initial implementation and mock name given. This is useful when you want to completely restore a mock back to its initial state.

Furthermore, I also add a new test for another view. I been explore several files that related with the test and try to know and understand the component that are correlate with the test. In conclusion, I want to thank Peter for his suggestions and the chance to learn more about writing test cases. Even though I occasionally find it difficult, I am eager to keep developing and expanding my knowledge.

Testing Update and Delete Command

Last week, early in the week, I focused on testing the update command handler for an entity. I conducted a total of 6 tests. The first test verified the successful update of an entity without contact information. I checked the HTTP status code returned by the update API, which should be 200 (OK). I also made assertions on the updated data to ensure the changes were applied correctly.

The second test handled scenarios where an update was attempted on an entity with an invalid ID. The update API was called with an invalid ID, and the application was expected to return a 400 (BadRequest) status code. The test also validated the error message received against the expected error message for an invalid entity.

I also conducted tests focusing on updating entities with various contact scenarios. This included updates involving multiple contacts, a single contact, and adding new contacts while retaining existing ones. The last test addressed cases where duplicate contacts were provided during the update process. By intentionally supplying duplicate contacts, I expected the application to detect this duplication and return a 400 (BadRequest) status code. The error message received was also validated against the expected error message for duplicate contacts.

After completing the tests for the update command handler, I moved on to the next task, which involved implementing the delete command. This command encapsulates the necessary information to delete an entity, including identification, associated user, code, name, creation timestamp, ID, contact details, and default settings. To handle the delete command, I implemented the delete command handler, which is responsible for processing the command.

The handler uses a service interface to perform the deletion of the entity. The delete command is first validated using the delete command validator, ensuring that required fields such as the entity’s ID are provided and valid. If the command passes validation, I retrieve the entity using its ID from the service interface. If the entity is not found, an exception indicating an invalid entity is thrown. If the entity exists, a transaction is initiated to delete the entity by invoking the appropriate method on the service interface. After successful deletion, the transaction is completed by performing an audit using the provided ID.

To ensure the correctness of the implementation, I created two unit tests for the delete command. The first test verifies the successful deletion of a valid entity. It retrieves the entity from the service, sends a delete request to the API endpoint, and asserts that the entity no longer exists after deletion.

The second test checks the behavior when attempting to delete an entity with an invalid ID. It sends a delete request to the API endpoint with an invalid ID and asserts that a BadRequest response is received. The response is then deserialized into an ErrorDto object, and the error message is checked against the expected error message for an invalid ID.

For this week, my focus will be on continuing on Get command implementation. Additionally, I will also begin on learning and familiarizing myself with the UI, as instructed by Mr. Peter.

Update Command Handler

In the previous week, after I finished a task of create command handler for an entity, I continued on the next part which is the update command handler, which is for handling update operations on the entity. The update command handler plays a crucial role in ensuring that the entity’s data remains accurate and up to date.

Initially, I assumed that the command handler for creating and updating entities would follow a similar pattern. However, Mr. Peter pointed out the distinct responsibilities of the update command handler, prompting me to gain a deeper understanding of its requirements. One of the challenges I faced was developing a method to identify the exact entity instance that needed to be updated. Considering that the update operation can impact various properties of the entity, it was crucial to adopt a robust approach capable of handling different update scenarios effectively.

To address this challenge, I implemented the FirstOrDefault() method, allowing me to locate the ID of the entity instance intended for modification. This approach ensured that the update command handler acted on the correct data, precisely targeting the entity in question. Additionally, I prioritized improving the update command handler’s overall functionality by incorporating error handling mechanisms. I implemented appropriate exception handling and error reporting to provide clear and informative feedback to users in case of any issues during the update operation. This helped in facilitating prompt troubleshooting and resolution of any potential problems.

Moving forward next week, I plan to continuously refine and optimize the update command handler, particularly during the unit testing phase, as it provides valuable insights into the evolving requirements.

Mock Implementation in Testing

Hello there, hope you have a nice day. It is time for my weekly task update. For the past week, I have been working on to implement mock for the test cases.

First and foremost, what is mock? Mock in software testing is an object that mimics the behavior of a real object in a controlled way. Next, mock also is a process used in testing when the unit being tested has external dependencies. In addition, the implementation of mock used to test the interaction between objects and simulate certain conditions that might be difficult or impossible to reproduce in a real-world environment. Mock functions used to test the links between code by erasing the actual implementation of a function. Next, it use to capturing calls to the function. Other than that, capturing instances of constructor function when instantiated with new.

Next, for the first mock implementation, I tried to implement mock in focus. For this test case, the purpose is to mock the focus method of the element and triggers a focus event on it. Then, for the next test case, I tried to implement mock for React Navigation. For this mock implementation, I have been using spread syntax to replace the navigation method. The spread syntax is a syntax for copying the properties of an object into a new object. This is crucial in testing to make sure the original item has not been altered.

Overall, I want to thank Peter for his advice and the opportunity to learn more about the use of mock tests in testing. Despite the fact that it can be challenging for me at times, I am eager to keep growing and learning new things.

Exploring Unit Testing for Entity Creation

Last week, I was fully focused on testing the Create Command functionality of an entity. Along the way, I gained a deeper understanding of the importance of unit testing. Creating unit tests allowed me to explore different scenarios and cover as many possibilities as possible with the guidance of Mr. Peter.

In the initial test, I ensured that an entity could be created successfully even without providing any contact details. The accuracy of saving the entity information in the database was verified, along with confirming the receipt of the expected response. Building on that, the next test included a phone contact. I validated that the entity and contact details were accurately saved and associated with each other.

Moreover, with Mr. Peter’s expert guidance, I took on the challenge of creating an entity with multiple entity contacts, then specifically designating one of them as the phone contact. His insights helped me navigate the complexities involved in ensuring the proper association of the chosen contact with the entity and the flawless storage of all entity contacts in the database. Throughout these tests, to validate the expected behavior of the test methods, I used the FluentAssertions library, making assertions with confidence.

Overall, this tests successfully validated the entity creation and contact management functionalities. These tests covered a range of scenarios, including entities without contacts, entities with phone contacts, entities with multiple contacts, and entities with fax contacts. The results obtained from these tests provide a solid foundation for maintaining the integrity of the entity-related features within the application.

Test Case Problems

Hi there, hope you have a nice day. For the past week, I have been working on doing some changes for my test case. Focusing on do a little changes and add some new methods to make the test case passed without errors.

Firstly, for my first test case which is test on scanning of correct code should navigate back to the list view. For example, when the user enter the correct code it will automatically navigate back to the list view. Apart from that, Peter help me to mock the test suite globally. There are times where we need to mock functions like fetch for example, etc., globally instead of mocking individually in each file. Node Package Manager (NPM) modules like jest-fetch-mock, etc., are there for rescue to mock these globally. With this approach, we can mock any API globally that we need to.

Next, for my second test case which is test on scanning of incorrect code should prompt error box and navigate back. For example, when the user enter the incorrect code, the prompt error box will pop-up and show invalid. At first for this test case, I get an error on test id. The error cause from my silly mistake which is I get the test id from another file which is the incorrect one. After that, Peter showed me the correct file which is I should take the test id. I am grateful and thanks to Peter for helping me to solve the problems.

Overall I am thankful to Peter and also to learn more about writing a test case. I am keen to keep improving and learning new things, even though it can be difficult for me at times.

Tough in handling a test case

Hello everyone, I hope you are doing well out there. It is time for my weekly task update. It is continue for my last week task which is writing a Test Suite. For this week, I have been focusing on make a correction for scanning of correct code should navigate back to list view.

Firstly, like I mention before this I have been handling with the scanning a correct location code should navigate back to the list view. For this test case it is not that quite challenging but throughout writing and make a correction for this test case I have been deal with several issues and errors. Like the past week, for this test case I have been dealing with the function or method issue. But after few tries and error, I managed to solve the issue by mock it. I use jest function to mock it and the issue is resolved after the mock implementation in the test case.

Furthermore, I run and debug the test case to make sure there is no other issues and errors. New issues are pop up after the running and debugging the test case. For this issue it involved the sound library. This issue really make me feel blank because I have been explore and also refer another file to solve it. After several try and error the issue did not resolve. After that I ask Peter for some help and code review. At first we also take some time to solve the sound issue. It is because the value in the test id is null. We also tried several method in order to make the input element editable. But in the end the value is still null after debugging it.

Overall, this week is not easy for me. I hope next week I manage to make the test suite pass. I also thankful for the opportunity to learn from Peter and helping me throughout on writing this test suite.

Unit Testing

Once the creation of Create command for an object was finished, I continued on building the unit test. Unit testing is an important part of software development because it helps to ensure that the code is working correctly and meets the requirements of the system we’re building.

Unit testing is also crucial for maintaining the quality of code over time. It allows developers to test new features or changes made to the system and detect any regression bugs or unexpected side effects.

To test the Create command, I started with the simplest test. Firstly, in the unit test, I created a test environment for the application to run in. Then, I initialized a set of data by creating an array of entity objects and added them to the database using the AddRange() method then called SaveChanges() method to save the changes to the database.

Next, I created a new test method that simulated the creation of a new object by sending a POST request to the object controller API endpoint with a CreateCommand object containing the necessary details. The test method checked whether the response status code was OK, which confirmed that the object was successfully created. It also checked whether the created object ID was not equal to 0, which confirmed that a new object was indeed created. Additionally, the test method checked whether the number of objects in the database increased by one by retrieving the count of objects before and after the creation of the new object using the AsNoTracking method.

To summarize, unit testing plays a critical role in verifying that the code is functioning correctly and meets the system requirements. Moving forward next week, I will continue creating unit tests, to detect any bugs or errors early on. By thoroughly testing the system, I can ensure that it functions as intended and meets the necessary specifications.