Sunday, May 24, 2020

How to use ReflectionTestUtils in junit

How to use ReflectionTestUtils.setField() in Junit?

Q- What is ReflectionTestUtils in junit?
Ans: ReflectionTestUtils is a collection for reflection-based utility methods used in junit. it is a part of Spring Test Context framework. ReflectionTestUtils is use to inject dependencies for integration testing scenarios to set the non-public fields, invoke non-public methods.

Q- How to Mock an Autowired @Value field in Spring with Junit Mockito

Ans- We can set value to aitowired @Value fields using RefectionTestUtils‘s setField() method.
for example you are using some properties from property file using @Value annotation.

Lets see below example for ReflectionTestUtills.setField()

package com.example.user.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.example.user.model.Account;

@Service
public class AccountServiceImpl implements AccountService {

 @Value("${account.name}")
 private String accountName;

 @Value("${account.number}")
 private String accountNumber;

 public Account getAccountDetails() {
  Account account = new Account();
  account.setAccountName(accountName);
  account.setAccountNumber(accountNumber);
  return account;
 }
}

package com.example.user.service;

import static org.junit.Assert.assertEquals;

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;

import com.example.user.model.Account;

@RunWith(MockitoJUnitRunner.class)
public class AccountServiceImplTest {

 @Spy
 private final AccountServiceImpl accountservice = new AccountServiceImpl();

 @Before
 public void setUp() {
  // best way to setFields is in setUp() method even we can also set same in test
  // method as well
  ReflectionTestUtils.setField(accountservice, "accountName", "Test");
  ReflectionTestUtils.setField(accountservice, "accountNumber", "123654789");
 }

 @Test
 public void testgetGrtAccountDetails() throws Exception {
  // we can also set setField Here
  // ReflectionTestUtils.setField(accountservice, "accountName", "Test");
  // ReflectionTestUtils.setField(accountservice, "accountNumber", "123654789");

  Account account = accountservice.getAccountDetails();
  assertEquals(account.getAccountName(), "Test");
  assertEquals(account.getAccountNumber(), "123654789");
  Mockito.verify(accountservice, Mockito.times(1)).getAccountDetails();
 }
}

No comments:

Post a Comment