question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Constructor Injection is not injecting Optional

See original GitHub issue
  • The mockito message in the stacktrace have useful information, but it didn’t help
  • The problematic code (if that’s possible) is copied here; Note that some configuration are impossible to mock via Mockito
  • Provide versions (mockito / jdk / os / any other relevant information)
  • Provide a Short, Self Contained, Correct (Compilable), Example of the issue (same as any question on stackoverflow.com)
  • Read the contributing guide

Having this code snippet:

@RunWith(MockitoJUnitRunner.class)
public class OptionalInjectionTest
{

    public static class Foo {}

    public static class Bar {
        private final Foo foo;
        public Bar(final Optional<Foo> foo) {
            System.out.println("Foo is "+foo);
            this.foo = foo.orElse(null);
        }
    	public Foo getFoo() {
            return foo;
        }
    }

    @Mock
    private Foo foo;

    @InjectMocks
    private Bar bar;

    @Test
    public void testInjectOptional()
    {
        assertNotNull(bar);
        assertNotNull(bar.getFoo());
    }
}

Running the test throws:

org.mockito.exceptions.misusing.InjectMocksException: 
Cannot instantiate @InjectMocks field named 'bar' of type 'class com.mycompany.app.OptionalInjectionTest$Bar'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null

Mockito injects null, while instead it should Inject Optional[foo] (or if Foo Mock is not found - empty Optional[])

Info: Mockito: 3.1.0 JDK: 1.8 OS: WIN10

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:11 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
bric3commented, Jan 20, 2020

What @TimvdLippe ment is this

	private Foo foo;
	private Bar bar;

	@Before
	public void setUp() {
                foo = mock(Foo.class);
		bar = new Bar(Optional.of(foo));
	}
0reactions
Prayticcommented, Oct 4, 2021

How can I do the same with annotations? I have a huge constructor with 20 values and 1 optional. Because of it I need to write this huge constructor in @Before method?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why You Should Use Constructor Injection in Spring
Constructor injection helps in creating immutable objects because a constructor's signature is the only possible way to create objects. Once we ...
Read more >
Optional Dependency Injection using Spring
This guide walks through the options available to inject optional dependencies with Spring DI. Introduction. There are quite a few use-cases ...
Read more >
Setter injection versus constructor injection and the use of ...
For those exact two reasons, I think constructor injection is much more usable for application code than it is for framework code.
Read more >
How to handle optional service dependency ... - Stack Overflow
1 Answer 1 ... You have three ways to achieve this. ... This works, but it requires field injection, which is not great...
Read more >
Optional Dependency Injection Using Spring - DZone Java
... ways to inject optional dependencies within a Spring DI application, ... infrastructure dependency is not provided, such as DataSources.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found