How to mock Optional bean in spring boot? - java

In my SpringBootApplication, I have a bean which injects another optional bean (like shown below)
#Service
public class A {
//B is another #Component from one of the dependencies
private Optional<B> b;
...
...
}
I am writing an integration test for class A where I need to #MockBean Optional<B> b. However since Optional is a final class, spring mockito raises following error
Cannot mock/spy class java.util.Optional
- final class
Is there a way around this? Any help is much appreciated.

You can use Optional.of(b).
If you use mockito with annotations, then you can't use #InjectMocks because your optional will not be known for mockito. You have to create your service A yourself. Something like this:
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#Mock
private B b;
private A a;
#Before
public void setup() {
a = new A(Optional.of(b));
}
}

You should actually mock the actual bean using #MockBean or #MockBeans or TestConfig class and Autowire the Optional with mocked bean
#Autowired
private Optional<B> OptionalB;
#MockBean
private B b;

Although Lino's above answer works perfectly, I chose not to modify the production code to make the test work. I've instead modified my code like below:
#Service
public class A {
#Autowired(required = false)
private B b;
...
...
}

Related

How to mock methods which has defined/fixed/hardcoded input?

I have a method in a class lets say doStuff which calls another method of another class execute:
#Component
class A {
#Autowired
B b;
int doStuff(){
return b.execute(1);
}
}
#Component
class B {
int execute(int i){
return i;
}
}
Now when I'm trying to mock the method execute, it is throwing nullPointer
#ExtendWith(MockitoExtension.class)
public class ATest{
#InjectMocks
A a;
#Mock
B b;
#Test
doStuffTest(){
when(b.execute(anyInt()).thenReturn(1);
assertEquals(1,a.doStuff());
}
}
It is throwing NullPointer Exception on line when(b.execute(anyInt()).thenReturn(1);
#Autowired annotation is part of Spring, while #Mock is part of Mockito. #Autowired will not be triggered using the Mockito test. Mocked class has to be a constructor where object can be injected by #InjectMock.
If you want to use #Autowired you need a Spring context like #SpringBootTest or others that scan and configuration your project. So, if you would like to mock this bean, you will have to #MockBean annotation.
Issue resolved with #RunWith(MockitoJUnitRunner.class) annotation, without that it's failing

Why #MockBean does not mock my target repository class (returns null)?

Here is the class I want to test
#Component
public class PermissionCheck {
#Autowired
private MyEntityRepository myEntityRepository;
public boolean hasPermission(int myEntityID) {
MyEntity myEntity = myEntityRepository.findById(myEntityId);
return myEntity != null;
}
}
Here is the test class
#RunWith(SpringRunner.class)
public class PermissionCheckTests {
#MockBean
private MyEntityRepository myEntityRepository;
private PermissionCheck permissionCheck;
#Before
public void before() {
this.permissionCheck = new PermissionCheck();
}
#Test
public void shouldHasPermission() {
MyEntity myEntity = new MyEntity();
when(this.myEntityRepository.findById(any())).thenReturn(myEntity);
assertTrue(this.permissionCheck.hasPermission(0));
}
}
And when I run this test I got
java.lang.NullPointerException
at PermissionCheck.hasPermission(PermissionCheck.java:line1)
at PermissionCheckTests.shouldHasPermission(PermissionCheckTests.java:line2)
In the above, line1 and line2 refer to these two lines
MyEntity myEntity = myEntityRepository.findById(myEntityId);
assertTrue(this.permissionCheck.hasPermission(0));
And using debugger I see that when entering PermissionCheck.hasPermission from PermissionCheckTests.shouldHasPermission, the repository field
#Autowired
private MyEntityRepository myEntityRepository;
is null.
I created these classes by referring to others existing codes, from different places, and without really understanding how to the annotations (partially due to running out of time), so if someone can tell me not only how to fix, but also why I'm wrong, I would really appreciate it!
Edit:
I made the change suggested by #Nikolas Charalambidis (thank you!), so my PermissionCheck class now looks exactly like
#RunWith(SpringRunner.class)
public class PermissionCheckTests {
#Autowired // you need to autowire
private PermissionCheck permissionCheck; // and it uses #MockBean dependency
#MockBean // if no such #MockBean exists
private MyEntityRepository myEntityRepository; // the real implementation is used
#Test
public void shouldHasPermission() {
MyEntity myEntity = new MyEntity();
when(this.myEntityRepository.findById(any())).thenReturn(myEntity);
assertTrue(this.permissionCheck.hasPermission(0));
}
}
But I then got the following exception
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'PermissionCheckTests':
Unsatisfied dependency expressed through field 'permissionCheck';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'PermissionCheck' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value="")}
With a little bit search, from this SO answer, I feel like I should not #Autowired PermissionCheck, since it is a class, not an interface.
Does that mean I have to create an interface, #Autowired it and let PermissionCheck implement it? It seems redundant to me, since I don't see why I need such an interface. Is there a way to make it work without creating a new interface which I will solely use for this purpose?
The instance of class PermissionCheck is not properly injected. The tests use the Spring container in the same way as the production code. The following line would not inject the myEntityRepository.
this.permissionCheck = new PermissionCheck();
Spring: NullPointerException occurs when including a bean partly answers your question. You need to #Autowire the thing.
The Spring test context is no different. As long as #MockBean MyEntityRepository exists as a mocked bean, the PermissionCheck will be autowired in the standard way using the mocked class in precedence over the existing bean in the test scope.
#RunWith(SpringRunner.class)
public class PermissionCheckTests {
#Autowired // you need to autowire
private PermissionCheck permissionCheck; // and it uses #MockBean dependency
#MockBean // if no such #MockBean exists
private MyEntityRepository myEntityRepository; // the real implementation is used
#Test
public void shouldHasPermission() {
MyEntity myEntity = new MyEntity();
when(this.myEntityRepository.findById(any())).thenReturn(myEntity);
assertTrue(this.permissionCheck.hasPermission(0));
}
}
in my case i was using lombok i was added #NoArgsConstructor
to the class that that i had injected my repository.
#Component
#AllArgsConstructor
#NoArgsConstructor // what cuased the null pointer
public class ParcelUtil {
private final Logger log = LoggerFactory.getLogger(OrderEventConsumer.class);
private ParcelRepository parcelRepository;
}
my test:
#SpringBootTest
#DirtiesContext
public class OrderEventConsumerTest extends SpringBootEmbeddedKafka {
#MockBean
private ParcelRepository parcelRepository;
}
#Test
public void update_parcel_inride_to_delivered_nxb() throws JsonProcessingException {
//given
List<Parcel> parcels = DataUtil.createParcel_inride_and_draft_nxb();
Mockito
.when(parcelRepository.findFirstByParcelGroupId("12"))
.thenReturn(Optional.ofNullable(parcels.get(0))); //where i got null pointer
}
}

Can't inject Bean (child of #Spy injected bean) in my Test

When I'm making a Test, I can't get injected a property of one of the injected beans (with #Spy). I am using Mockito to test.
I tried using #Mock, #Spy, #SpyBean and #InjectMocks in this Bean on my test but I can't get it injected.
#RunWith(MockitoJUnitRunner.class)
public class MyTest{
#InjectMocks private MyService = new myService();
#Spy private MyFirtsDepen firstDepen;
#Autowired #Spy private ChildDepen childDepen;
... More mocks and tests
}
#Service
public class MyService {
#Autowired private MyFirstDepen firstDepen;
....
}
#Mapper
public class MyFirstDepen {
#Autowired private ChildDepen childDepen;
....
}
#Component
public class ChildDepen {
...
}
When my test use firstDepen is working great, but when firstDepen uses childDepend always get Nullpointer. How can I inject this property in my test?
Since your MyFirtsDepen is a mock, there is no way to inject anything to it. Configure mock to return another mock.
when(firstDepen.getChildDepen()).doReturn(childDepen);

Injecting a String property with #InjectMocks

I have a Spring MVC #Controller with this constructor:
#Autowired
public AbcController(XyzService xyzService, #Value("${my.property}") String myProperty) {/*...*/}
I want to write a standalone unit test for this Controller:
#RunWith(MockitoJUnitRunner.class)
public class AbcControllerTest {
#Mock
private XyzService mockXyzService;
private String myProperty = "my property value";
#InjectMocks
private AbcController controllerUnderTest;
/* tests */
}
Is there any way to get #InjectMocks to inject my String property? I know I can't mock a String since it's immutable, but can I just inject a normal String here?
#InjectMocks injects a null by default in this case. #Mock understandably throws an exception if I put it on myProperty. Is there another annotation I've missed that just means "inject this exact object rather than a Mock of it"?
You can't do this with Mockito, but Apache Commons actually has a way to do this using one of its built in utilities. You can put this in a function in JUnit that is run after Mockito injects the rest of the mocks but before your test cases run, like this:
#InjectMocks
MyClass myClass;
#Before
public void before() throws Exception {
FieldUtils.writeField(myClass, "fieldName", fieldValue, true);
}
Since you're using Spring, you can use the org.springframework.test.util.ReflectionTestUtils from the spring-test module. It neatly wraps setting a field on a object or a static field on a class (along with other utility methods).
#RunWith(MockitoJUnitRunner.class)
public class AbcControllerTest {
#Mock
private XyzService mockXyzService;
#InjectMocks
private AbcController controllerUnderTest;
#Before
public void setUp() {
ReflectionTestUtils.setField(controllerUnderTest, "myProperty",
"String you want to inject");
}
/* tests */
}
You cannot do this with Mockito, because, as you mentioned yourself, a String is final and cannot be mocked.
There is a #Spy annotation which works on real objects, but it has the same limitations as #Mock, thus you cannot spy on a String.
There is no annotation to tell Mockito to just inject that value without doing any mocking or spying. It would be a good feature, though. Perhaps suggest it at the Mockito Github repository.
You will have to manually instantiate your controller if you don't want to change your code.
The only way to have a pure annotation based test is to refactor the controller. It can use a custom object that just contains that one property, or perhaps a configuration class with multiple properties.
#Component
public class MyProperty {
#Value("${my.property}")
private String myProperty;
...
}
This can be injected into the controller.
#Autowired
public AbcController(XyzService xyzService, MyProperty myProperty) {
...
}
You can mock and inject this then.
#RunWith(MockitoJUnitRunner.class)
public class AbcControllerTest {
#Mock
private XyzService mockXyzService;
#Mock
private MyProperty myProperty;
#InjectMocks
private AbcController controllerUnderTest;
#Before
public void setUp(){
when(myProperty.get()).thenReturn("my property value");
}
/* tests */
}
This is not pretty straight forward, but at least you will be able to have a pure annotation based test with a little bit of stubbing.
Just don't use #InjectMocks in that case.
do:
#Before
public void setup() {
controllerUnderTest = new AbcController(mockXyzService, "my property value");
}
Solution is simple: You should put constructor injection for the object type while for primitive/final dependencies you can simply use setter injection and that'll be fine for this scenario.
So this:
public AbcController(XyzService xyzService, #Value("${my.property}") String myProperty) {/*...*/}
Would be changed to:
#Autowired
public AbcController(XyzService xyzService) {/*...*/}
#Autowired
public setMyProperty(#Value("${my.property}") String myProperty){/*...*/}
And the #Mock injections in test would be as simple as:
#Mock
private XyzService xyzService;
#InjectMocks
private AbcController abcController;
#BeforeMethod
public void setup(){
MockitoAnnotations.initMocks(this);
abcController.setMyProperty("new property");
}
And that'll be enough. Going for Reflections is not advisable!
PLEASE AVOID THE USAGE OF REFLECTIONS IN PRODUCTION CODE AS MUCH AS POSSIBLE!!
For the solution of Jan Groot I must remind you that it will become very nasty since you will have to remove all the #Mock and even #InjectMocks and would have to initialize and then inject them manually which for 2 dependencies sound easy but for 7 dependencies the code becomes a nightmare (see below).
private XyzService xyzService;
private AbcController abcController;
#BeforeMethod
public void setup(){ // NIGHTMARE WHEN MORE DEPENDENCIES ARE MOCKED!
xyzService = Mockito.mock(XyzService.class);
abcController = new AbcController(xyzService, "new property");
}
What you can use is this :
org.mockito.internal.util.reflection.Whitebox
Refactor your "AbcController" class constructor
In your Test class "before" method, use Whitebox.setInternalState method to specify whatever string you want
#Before
public void setUp(){
Whitebox.setInternalState(controllerUnderTest, "myProperty", "The string that you want"); }
If you want to have no change in your code then use ReflectionTestUtils.setField method
How do I mock an autowired #Value field in Spring with Mockito?

Difference between #Mock and #InjectMocks

What is the difference between #Mock and #InjectMocks in Mockito framework?
#Mock creates a mock. #InjectMocks creates an instance of the class and injects the mocks that are created with the #Mock (or #Spy) annotations into this instance.
Note you must use #RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4).
With JUnit 5, you must use #ExtendWith(MockitoExtension.class).
#RunWith(MockitoJUnitRunner.class) // JUnit 4
// #ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {
#InjectMocks
private SomeManager someManager;
#Mock
private SomeDependency someDependency; // this will be injected into someManager
// tests...
}
This is a sample code on how #Mock and #InjectMocks works.
Say we have Game and Player class.
class Game {
private Player player;
public Game(Player player) {
this.player = player;
}
public String attack() {
return "Player attack with: " + player.getWeapon();
}
}
class Player {
private String weapon;
public Player(String weapon) {
this.weapon = weapon;
}
String getWeapon() {
return weapon;
}
}
As you see, Game class need Player to perform an attack.
#RunWith(MockitoJUnitRunner.class)
class GameTest {
#Mock
Player player;
#InjectMocks
Game game;
#Test
public void attackWithSwordTest() throws Exception {
Mockito.when(player.getWeapon()).thenReturn("Sword");
assertEquals("Player attack with: Sword", game.attack());
}
}
Mockito will mock a Player class and it's behaviour using when and thenReturn method. Lastly, using #InjectMocks Mockito will put that Player into Game.
Notice that you don't even have to create a new Game object. Mockito will inject it for you.
// you don't have to do this
Game game = new Game(player);
We will also get same behaviour using #Spy annotation. Even if the attribute name is different.
#RunWith(MockitoJUnitRunner.class)
public class GameTest {
#Mock Player player;
#Spy List<String> enemies = new ArrayList<>();
#InjectMocks Game game;
#Test public void attackWithSwordTest() throws Exception {
Mockito.when(player.getWeapon()).thenReturn("Sword");
enemies.add("Dragon");
enemies.add("Orc");
assertEquals(2, game.numberOfEnemies());
assertEquals("Player attack with: Sword", game.attack());
}
}
class Game {
private Player player;
private List<String> opponents;
public Game(Player player, List<String> opponents) {
this.player = player;
this.opponents = opponents;
}
public int numberOfEnemies() {
return opponents.size();
}
// ...
That's because Mockito will check the Type Signature of Game class, which is Player and List<String>.
In your test class, the tested class should be annotated with #InjectMocks. This tells Mockito which class to inject mocks into:
#InjectMocks
private SomeManager someManager;
From then on, we can specify which specific methods or objects inside the class, in this case, SomeManager, will be substituted with mocks:
#Mock
private SomeDependency someDependency;
In this example, SomeDependency inside the SomeManager class will be mocked.
#Mock annotation mocks the concerned object.
#InjectMocks annotation allows to inject into the underlying object the different (and relevant) mocks created by #Mock.
Both are complementary.
#Mock creates a mock implementation for the classes you need.
#InjectMock creates an instance of the class and injects the mocks that are marked with the annotations #Mock into it.
For example
#Mock
StudentDao studentDao;
#InjectMocks
StudentService service;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
Here we need the DAO class for the service class. So, we mock it and inject it in the service class instance.
Similarly, in Spring framework all the #Autowired beans can be mocked by #Mock in jUnits and injected into your bean through #InjectMocks.
MockitoAnnotations.initMocks(this) method initialises these mocks and injects them for every test method so it needs to be called in the setUp() method.
This link has a good tutorial for Mockito framework
A "mocking framework", which Mockito is based on, is a framework that gives you the ability to create Mock objects ( in old terms these objects could be called shunts, as they work as shunts for dependend functionality )
In other words, a mock object is used to imitate the real object your code is dependend on, you create a proxy object with the mocking framework.
By using mock objects in your tests you are essentially going from normal unit testing to integrational testing
Mockito is an open source testing framework for Java released under the MIT License, it is a "mocking framework", that lets you write beautiful tests with clean and simple API. There are many different mocking frameworks in the Java space, however there are essentially two main types of mock object frameworks, ones that are implemented via proxy and ones that are implemented via class remapping.
Dependency injection frameworks like Spring allow you to inject your proxy objects without modifying any code, the mock object expects a certain method to be called and it will return an expected result.
The #InjectMocks annotation tries to instantiate the testing object instance and injects fields annotated with #Mock or #Spy into private fields of the testing object.
MockitoAnnotations.initMocks(this) call, resets testing object and re-initializes mocks, so remember to have this at your #Before / #BeforeMethod annotation.
Though the above answers have covered, I have just tried to add minute detail s which i see missing. The reason behind them(The Why).
Illustration:
Sample.java
---------------
public class Sample{
DependencyOne dependencyOne;
DependencyTwo dependencyTwo;
public SampleResponse methodOfSample(){
dependencyOne.methodOne();
dependencyTwo.methodTwo();
...
return sampleResponse;
}
}
SampleTest.java
-----------------------
#RunWith(PowerMockRunner.class)
#PrepareForTest({ClassA.class})
public class SampleTest{
#InjectMocks
Sample sample;
#Mock
DependencyOne dependencyOne;
#Mock
DependencyTwo dependencyTwo;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
public void sampleMethod1_Test(){
//Arrange the dependencies
DependencyResponse dependencyOneResponse = Mock(sampleResponse.class);
Mockito.doReturn(dependencyOneResponse).when(dependencyOne).methodOne();
DependencyResponse dependencyTwoResponse = Mock(sampleResponse.class);
Mockito.doReturn(dependencyOneResponse).when(dependencyTwo).methodTwo();
//call the method to be tested
SampleResponse sampleResponse = sample.methodOfSample()
//Assert
<assert the SampleResponse here>
}
}
Reference
One advantage you get with the approach mentioned by #Tom is that you don't have to create any constructors in the SomeManager, and hence limiting the clients to instantiate it.
#RunWith(MockitoJUnitRunner.class)
public class SomeManagerTest {
#InjectMocks
private SomeManager someManager;
#Mock
private SomeDependency someDependency; // this will be injected into someManager
//You don't need to instantiate the SomeManager with default contructor at all
//SomeManager someManager = new SomeManager();
//Or SomeManager someManager = new SomeManager(someDependency);
//tests...
}
Whether its a good practice or not depends on your application design.
#Mock is used to declare/mock the references of the dependent beans, while #InjectMocks is used to mock the bean for which test is being created.
For example:
public class A{
public class B b;
public void doSomething(){
}
}
test for class A:
public class TestClassA{
#Mocks
public class B b;
#InjectMocks
public class A a;
#Test
public testDoSomething(){
}
}
#InjectMocks annotation can be used to inject mock fields into a test object automatically.
In below example #InjectMocks has used to inject the mock dataMap into the dataLibrary .
#Mock
Map<String, String> dataMap ;
#InjectMocks
DataLibrary dataLibrary = new DataLibrary();
#Test
public void whenUseInjectMocksAnnotation_() {
Mockito.when(dataMap .get("aData")).thenReturn("aMeaning");
assertEquals("aMeaning", dataLibrary .getMeaning("aData"));
}
Many people have given a great explanation here about #Mock vs #InjectMocks. I like it, but I think our tests and application should be written in such a way that we shouldn't need to use #InjectMocks.
Reference for further reading with examples: https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/
#Mock is for creating and injecting mock instances without having to call Mockito.mock manually. In this example the instance would be ClassB.
Whereas, #InjectMocks is for injecting mock fields into the tested object automatically. In this case it would be ClassA
Notice that that #InjectMocks are about to be deprecated
deprecate #InjectMocks and schedule for removal in Mockito 3/4
and you can follow #avp answer and link on:
Why You Should Not Use InjectMocks Annotation to Autowire Fields

Categories