DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • Testing Automation Antipatterns: When Good Practices Become Your Worst Enemy
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up

Trending

  • AI Agents for Software Engineering and Autonomous Development Workflows
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP
  • Why Role-Based Access Control Fails for AI Agents — and How to Fix It With Memory Lineage Engines
  • Threat Modeling Context-Aware AI: A STRIDE Walkthrough

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How to Unit Test Classes Which Create New Objects

How to Unit Test Classes Which Create New Objects

A simple method to write test cases for classes that use new keywords in their method with the help of Mockito and minimum code changes.

By 
Shivam Mohan
·
Updated Mar. 25, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
117.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

"Create"

Learn how to conduct effective unit tests.

First of all, I will start with a disclaimer that I am a strong proponent of using the simple factory programming idiom and by extension of using the Factory Method Pattern, instead of creating objects inside classes. The factory idiom helps you to insulate your code to changes thereby adhering to the Open to Extension Close to modification principle of object-oriented programming.

You may also like: Unit Testing: The Good, Bad, and Ugly

Also, the idea is to write testable code, not to write a hack to test code.

Having said that I will showcase a simple method to write test cases for classes that use new keywords in their method with the help of Mockito and minimum code changes.

Documentation link for Mockito.

The first step is to import Mockito dependencies into your code.

Java
 




x


 
1
<dependency>
2
   <groupId>org.mockito</groupId>
3
   <artifactId>mockito-core</artifactId>
4
   <version>2.23.0</version>
5
   <scope>test</scope>
6
</dependency>



Now let us see an example of how to test the class.

Let us assume the below is the class that we want to test.

Java
 




xxxxxxxxxx
1


 
1
public class ClassToBeTested {
2
    
3
    private ExternalClass object;
4

           
5
    public void MethodToTest() {
6
        object = new ExternalClass(arg1, arg2);
7
    }
8
}



Below is the sample class of the object that is instantiated in ClassToBeTested.

Java
 




xxxxxxxxxx
1


 
1
public class ExternalClass{
2
    private Object obj1;
3
    private Object obj2;
4
    public ExternalClass(Object arg1, Object arg2){
5
        this.obj1=arg1;
6
        this.obj2=arg2;
7
    }
8
}



The next step is to refactor the class to be tested and extract out the object instantiated into a separate method.

Java
 




xxxxxxxxxx
1
12


 
1
public class ClassToBeTested {
2

           
3
    private ExternalClass object;
4

           
5
    public ExternalClass makeExternalClassObject(Object arg1, Object arg2){
6
        return new ExternalClass(arg1, arg2);
7
    }
8

           
9
    public void MethodToTest() {
10
        object = makeExternalClassObject(arg1, arg2);
11
    }
12
}



One point to remember here is to avoid any logic in the make method so that we don’t have to write a unit test for this method.

Now let us write the test case for testing MethodToTest.

Java
 




xxxxxxxxxx
1
14


 
1
@RunWith(MockitoJUnitRunner.class)
2
public class ClassToBeTestedTest {
3
    @Mock private ExternalClass externalClass;
4

           
5
    @Test
6
    public void testMethodToBeTested(){
7
        ClassToBeTested classToBeTestedSpy = Mockito.spy(new ClassToBeTested());
8
        Mockito.doReturn(externalClass).when(classToBeTestedSpy)
9
                .makeExternalClassObject(arg1,arg2);
10
        classToBeTestedSpy.MethodToTest();
11
        /*Assertion Statement */
12

           
13
    }
14
}



Done! With this trick, we can write unit tests even for classes that have object instantiations in their implementation. Given that implementing the factory pattern is not feasible or not worth the effort.

Thanks!

Follow me on twitter at @IamShivamMohan

Further Reading

How to Automate a Java Unit Test, Including Mocking and Assertions

Creating Test Stages With JUnit

An Introduction to JUnit

unit test Java (programming language) Test case Mockito Test automation

Opinions expressed by DZone contributors are their own.

Related

  • Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • Testing Automation Antipatterns: When Good Practices Become Your Worst Enemy
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook