Introduction

The below example will show you how to mock an Autowired @Value field in Spring with Junit Mockito. Generally we read some configuration values from properties file into Spring bean or component class using @Value annotated attributes but when we want to test such service or component class using Junit test class then it is required to pass values for those autowired fields.

Now it is really cumbersome to place a properties file and read configuration values into those fields. Therefore Spring provides an easy mechanism to set values to aitowired @Value fields using RefectionTestUtils‘s setField() method.

Basically you need to pass three parameters as values into this method. The first parameter’s value indicates the class instance for which you want to set value to the autowired field. The second parameter’s value indicates the class attribute name for which you want to set the value. The final or third parameter’s value indicates the actual value that will be set to the class attribute.

Therefore you are basically mocking the @Value attribute using Spring’s ReflectionTestUtils API.

The below example shows how to mock an autowired @Value field in Spring with Junit mockito framework.

Prerequisites

Eclipse Neon, Java 1.8, Junit 4.12, Spring Boot 2.1.6, Mockito 2.23.4, Hamcrest 1.3, Gradle 5.4.1

Example with Source Code

In the below implementation we assume that you have a basic spring project setup knowledge in Eclipse.

Creating Project

Create a gradle based project in Eclipse, the project structure may look to the similar image.

mock an autowired value field in spring with junit mockito

Updating Build Script

Update the default generated build.gradle file with the following script to include the required dependencies for our application.

apply plugin: 'java'
repositories {
    mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
	compile("org.springframework:spring-core:5.1.8.RELEASE")
	compile("org.springframework:spring-context:5.1.8.RELEASE")
	testCompile("org.springframework:spring-test:5.1.8.RELEASE")
	testCompile('junit:junit:4.12') {
            exclude module : 'hamcrest'
            exclude module : 'hamcrest-core'
        }
	testCompile('org.hamcrest:hamcrest-core:1.3')
        testCompile('org.mockito:mockito-core:2.23.4')
}

Creating Service Class

Here we create one Spring service class that has an autowired @Value field and we will mock this field in our Junit class. We have also a simple method in this service class to verify the value of the autowired field we initialize into junit class.

package com.roytuts.junit.value.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class SpringJunitService {
	@Value("${security.key}")
	private String securityKey;
	public void updateValue() {
		System.out.println(securityKey);
	}
}

Creating Properties File

Create an application.properties file under classpath directory src/main/resources and put the below key/value pair into it.

security.key=SecurityKey

Creating Junit Class

We create the below junit class for the above service class.

Generally when we mock such field that is being used for entire class. Therefore, we need to initialize such field only once or before each test case executed. So if you need to initialize only once then you can put it using @BeforeClass annotation and if you need to execute before each class then you need to put it using @Before annotation.

Here in this example I have initialized the field using @Before annotation because I have only one test case.

Here we run the class with MockitoJunitRunner because we do not want to run integration test but mock test.

Notice how we do initialize our autowired field using ReflectionTestUtils.

We finally test the service class’s method and verify whether the method executed at least once using Junit’s verify() method.

package com.roytuts.junit.value.service;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
@RunWith(MockitoJUnitRunner.class)
public class SpringJunitValueTest {
	@Spy
	private final SpringJunitService springJunitService = new SpringJunitService();
	@Before
	public void setUp() {
		ReflectionTestUtils.setField(springJunitService, "securityKey", "it's a security key");
	}
	@Test
	public void testUpdateUser() throws Exception {
		springJunitService.updateValue();
		Mockito.verify(springJunitService, Mockito.times(1)).updateValue();
	}
}

You may read why we have used @Spy and Mockito.verify() in this example.

Testing the Application

Now run the Junit class, your Junit test will pass and you will get the following output in the console.

We have set the new value to the security key and displayed using updateValue() method.

it's a security key

Source Code

That’s all. Hope you got an idea how to mock an autowired @Value field in Spring with Junit mockito.

Thanks for reading.

Tags:

1 thought on “Mock an Autowired @Value field in Spring with Junit Mockito

Leave a Reply

Your email address will not be published. Required fields are marked *