Unit Testing Your Methods By Mocking Private Methods With JMockit Library

So you wrote some public methods which in turn call other private methods and you are asked to write junits for those public methods. But your private method calls do stuffs that you don’t want to test (for example, they might be trying to connect to a database). How would you then write a unit test for you public methods at the same time avoid stuffs that are done in the private methods?

In this tutorial, I will show you how you can use JMockit to mock the private methods. The main magic is, when you are mocking a private method, do not write the access modifier (private).

So instead of trying to mock the method the following way,

@Mock
private boolean doPrivateStuff() {
}

Use this one instead – no private:

@Mock
boolean doPrivateStuff() {
}

Here is the complete code.

package com.kushal.tools;

import mockit.Mock;
import mockit.MockUp;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * This class shows you how to Mock a private method.
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * www.icodejava.com
 *
 */

public class PrivateMethodMockTest {

    SomeClass object;
    @Before
    public void setup() {
        object = new SomeClass();
    }
    @SuppressWarnings("unused")
    @Test
    public void test_doPublicStuff_with_mocked_private_method() {
        new MockUp<SomeClass>() {
            @Mock
            boolean doPrivateStuff() {
                System.out.println("This is a mocked private method of class - SomeClass");
                
                /**
                 * Returning false from a mocked method
                 */
                return false; 
            }
        };
        
        boolean result = object.doPublicStuff();
        
        Assert.assertThat(result, CoreMatchers.is(false));
    }
    
    @Test
    public void test_doPublicStuff_with_no_mocking() {
        
        boolean result = object.doPublicStuff();
        
        Assert.assertThat(result, CoreMatchers.is(true));
    }
}

/**
 * This is a demo class whose public method will be tested.
 * Private method can be mocked.
 */
class SomeClass {
    
    public boolean doPublicStuff() {

        System.out.println("Inside doPublicStuff");
        /**
         * Call doPrivateStuff() method from this public method
         */
        return doPrivateStuff();
    }
    
    /**
     * Defining a private method that we want to mock with JMockit
     */
    private boolean doPrivateStuff() {
        System.out.println("Doing Some Private Stuff from Class - SomeClass");
        
        /**
         * Returning true from a real  method.
         */
        return true;
    }
    
}

Iterative development benefits in the Agile software development

Iterative Development in Agile Methodologies

Iterative Development in Agile Methodologies

As we know, the waterfall model of software engineering is getting obsolete day by day as more and more companies are choosing to go for the agile model of software development where they have seen lots of solid benefits by trying the agile and experimenting with variations of it to fit their own need. Agile is not rigid set of rules, although there are guiding principles.

So what are the benefits of using the iterative development also called sprints in Agile? Here are a few that I can think of.

  1. Iterative development in agile has a continuous focus on improving the processes.
  2. Iterative development pays attention to the quality of work, learning from what went bad and what things went good in prior iterations.
  3. Iterative development can help align or modify the priorities based on the outcome of the previous iteration deliveries.
  4. Business priorities and the business values can change all the time. Iterative development helps to adjust those values and priorities.
  5. With iterative development, the estimates get better as we grow. This estimate will be close to reality than the waterfall model of development where the estimations are done at the beginning of the project, which might not hold true as the project progresses.
  6. In the iterative development, there is opportunity to build the highest risk items first.
  7. Iterative development allows the testing to occur early and often.
  8. Iterative development allows to deliver the product early and deliver often.
  9. Risk discover, risk analysis and risk mitigation can occur earlier.
  10. Allows us to change the software even in the late cycle of development.
  11.  Because of the splitting of the task, the complexity in the iterations are manageable.
  12.  Iterative development helps produce early parrtial product which in turn can obtain early feedback and changes.
  13. With the continuous delivery and continous feedback, the final product becomes more closer to what user needs.
  14. Iterative development enforces better communication and engagement.
  15. Time boxed iterations give an idea of when to expect the delivery.

50 Things I Look For When I Do A Peer Code Review

(C) icodejava.com – Clean, well formatted, readable code.

I work as a tech lead for one of the fortune 500 companies, working with multitudes of developers on various projects. Some of these developers are fresh ones, others have come of age. Some of them are full time associates, while others are contractors who have seen various faces of software development styles at various other companies. In the end, everyone has their own coding styles, their own way of defining variables, their own way of writing classes and methods. Nobody purposefully wants to write bad code. Ultimately everyone tries to be a better coder.

Having said that, due to the varied nature of developers and their coding skills and styles, it becomes an important part of my role as a technical lead to make sure that the code that we are producing on a day to day basis are consistent, easy to read, are not nests for bugs, and are maintainable by people other than the ones who originally wrote them.

We work in an agile environments, pair programming kind of tends to do a first degree of code review by itself. But at times, I find myself still getting involved in a formal code review. Having worked on the enterprise application for several years, I do have a bigger picture of the application that some developers who are fresh hires. Coding clean is my passion. So when I start looking to peer’s work, I focus on certain standards of coding. Most of these standards are agreed upon by the team I work with and are implemented via static code analyzers such as Checkstyle. But it becomes necessary to remind to the new hires about these standards we follow. In this article, I am sharing 50 major things that I look at when I do a code review of my peer,co-worker, team mate.

  1. Does the code have proper error handling strategy? The common one being for the null pointer exception.
  2. Has the source code been properly formatted?
  3. Does every new method that is written have at least one unit test?
  4. Are there abbreviated variables or method names? I discourage using those. Variables, method names and class names must be meaningful.
  5. Are there any hard coded string literals? The string literals should be defined as constants.
  6. Is the method too long? Does it need to be split?
  7. Is the code efficient? For instance, are there any break statements in a for loop?
  8. Is the code repeated? If it is, then it’s time to refactor the code. Apply DRY – Don’t Repeat Yourself principle.
  9. Is the method having too many return statements?
  10. Are there too many if else conditions?
  11. Are there nested for loop? Every time there is a nested for loop, I recommend splitting that into two or more methods.
  12. Are there any default comments which add no values?
  13. Are there any TODO statements?
  14. Are the lines too long?
  15. Is the code consistent with rest of the code?
  16. Is the code readable?
  17. Is the code easy to follow through?
  18. Is the code maintainable? If someone else were to read the code and maintain it few years later, would it make sense?
  19. Are the resources, such as database connections, properly closed?
  20. Are there any tab characters? We have enforced to use spaces over tab characters in our team.
  21. Are there any unused imports?
  22. Is there any code with unhandled code warnings?
  23. Does the code have unused variables and methods?
  24. String Comparison. Does the code do CONSTANT.equals(variable) or varibale.equals(CONSTANT). The latter one can throw null pointer if variable is null. The former one does not.
  25. If you use static code analysis such as checkstyle, does the code introduce new warnings or errors?
  26. Does the code fail any unit tests?
  27. Are the variables public? variables must be private and have abstract methods.
  28. Is the file too long?
  29. Are there any empty methods?
  30. Do the methods have too many parameters?
  31. If the constructor definition in wrong order?
  32. Does the code catch the Exception class instead of the actual Exception such as NumberFormatException?
  33. Are there too many conditions being checked in an if statement?
  34. Are the variables and constants defined in correct order according to their visibility (public/private/protected/default).
  35. If you work on an agile environment, was there any pair programming done?
  36. Does the piece of code need performance testing?
  37. Is your method small? Does it do one thing and just one thing at a time based on your method name?
  38. If the code exposes any interfaces or APIs, are those clear and minimal?
  39. Is the proper level of abstraction used?
  40. If the code modified any existing logic, did the developer fix any existing issues such as abbreviated variable names in that method?
  41. Does the code use magic number such as 2,3,4 without stating what they mean?
  42. Does the code use magic strings such as “cp” (which could actually mean copy command) without stating what it means? The solution is to define description strings and use it, such as String COPY_COMMAND =”CP”;
  43. Does the class use a default package?
  44. Are there any variables defined within loops?
  45. Are there any variables defined that are used only once?
  46. Does the code use shared variables? Is the code thread safe?
  47. Is there any commented out code?
  48. Is the logging done properly, are there any left over System.out.println?
  49. Is the code clearly documented as needed? If the code is readable and flows through well, the needed documentation will be significantly less.
  50. Does a Switch / Case statement have a default?