~/java/21-how-mock-constructor-junit-test-case-development-issues.md

How to mock a constructor - Junit test case development issues

1 min readMarch 17, 2017by Gorav Singal#junit#java#mock
// TL;DR

Use PowerMock's whenNew() to mock constructors of objects instantiated inside a class under test, avoiding calls to external services like FTP or AWS during unit testing.

How to mock a constructor - Junit test case development issues

Introduction

While writing JUnit test cases, we encounter cases like we want to initialize a class, and that class instantiate a new class object which is an external entity class like FTP class or AWS service class. We do not want to initializethat external class object. In that cases, we would want to mock those objects.

Problem

We can mock any object in JUnit test code. But, what about the objects that are instantiated using new inside that class.

Example

class AmazonS3ServiceImpl {
	private AmazonS3Client amazonS3Client;

	public AmazonS3ServiceImpl() {
		this.amazonS3Client = new AmazonS3Client();
	}
}

Here, we would want to inject our mock object for AmazonS3Client, but how?

Solution

You need to annotate your JUnit test class with “@PrepareForTest” and mention both the classes you want to mock. See below:

@RunWith(PowerMockRunner.class)
@PrepareForTest({AmazonS3Client.class, AmazonS3ServiceImpl.class})
public class S3Test {
	@Before 
	public void setup() throws Exception {
		AmazonS3Client amazonS3Client = PowerMockito.mock(AmazonS3Client.class);
		PowerMockito.whenNew(AmazonS3Client.class).withParameterTypes(AWSCredentials.class).
			withArguments(Mockito.any()).thenReturn(amazonS3Client); //code for mocking Impl class
	}
}

Conclusion

So, we have informed Mocking system that whenever you are trying to instantiate a new object of AmazonS3Client class with AWSCredentials type parameter, return our mock object.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Linkage Error Loader Constraint Violation - JUnit test case development issue

Linkage Error Loader Constraint Violation - JUnit test case development issue

Its good to write unit tests cases, and this part is mostly forgotten by…

Java - Union and Intersection of two lists

Java - Union and Intersection of two lists

Suppose you have two lists, and you want Union and Intersection of those two…

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Introduction Java log4j has many ways to initialize and append the desired…

Fix: SAML Message Intended Destination Did Not Match Recipient

Fix: SAML Message Intended Destination Did Not Match Recipient

Introduction I was trying to integrate Okta with Spring, and when I deploy the…

Spring - Learn Multiple Ways to use PackageScan Annotation

Spring - Learn Multiple Ways to use PackageScan Annotation

Introduction In this post, we will see multiple ways to use annotation…

Spring Boot - Fixing Autowire Bean Not found

Spring Boot - Fixing Autowire Bean Not found

Introduction In a Spring boot app, we tend to use annotation, so that Spring…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…