Wednesday, February 21, 2018

Adding validation to a field and tested using mockMVC

The controller class ( has this code.

if (farmerIds.contains(farmerId)) {
farmerUnionRequest farmerUnionRequest = new farmerUnionRequest(farmerId, customerId);
                String encryptedRequest = encryptor.encrypt(StringUtil.toJsonString(farmerUnionRequest));
                response = redirectService.getConfirmAccountResponse(headers, ImmutableMap.of("encryptedUnionId", encryptedRequest));
 } else {
            LOG.warn("Unknown farmer id: {}", farmerId);
            response = new ResponseEntity("Unknown farmer id", BAD_REQUEST); 

I noticed that there is another main field called customerId and it is not checked for null or empty.
I changed the controller class like this.

if (farmerIds.contains(farmerId)) {
            if (!customerId.isEmpty()) { .  // isEmpty takes care of null as well as empty
                farmerFeedRequest farmerFeedRequest = new farmerFeedRequest(farmerId, customerId);
                String encryptedRequest = encryptor.encrypt(StringUtil.toJsonString(farmerFeedRequest));
                response = redirectService.getConfirmAccountResponse(headers, ImmutableMap.of("encryptedFeedId", encryptedRequest));

            } else {
                LOG.warn("Empty customer id for farmer id: {}", farmerId);
                response = new ResponseEntity("Unknown customer id", BAD_REQUEST);
        } else {
            LOG.warn("Unknown farmer id: {}", farmerId);
            response = new ResponseEntity("Unknown farmer id", BAD_REQUEST); /

But before I changed it, I added the following mockMVC test, failed it, wrote the code above to make the test pass, and created a pull request for review. This is TDD.

+    public void receiveFarmerRequestWithInvalidCustomerId() throws Exception {
+        MockHttpServletRequestBuilder request =
+                post("/api/farmersUnion")
+                        .param("farmerId", "ZER-123") // this is the correct id
+                        .param("clientId", "") // client id is empty
+                        .header("Content-Type", "application/json")
+                        .header("x-correlation-id", "correlationId");
+        mockMvc.perform(request).andExpect(status().isBadRequest());
+    }

Tuesday, February 20, 2018

Squashing the merges

When you want to merge into master, sometimes you want to squash all your commits (for that branch), so that they appear as a single commit on master.
You will always go into master and pull the changes from the branch.
Here are the git commands for you to do it.
Say your bug fix branch is called fixedAllBugs and you want to merge it into master:
git checkout master
git merge --squash fixedAllBugs
git commit