Mockito's #InjectMock annotation - bdd

I'm a little confused with #RunWith(MockitoJUnitRunner.class) and #InjectMock annotations and how they are related to each other. As per my understanding by giving #RunWith(MockitoJUnitRunner.class) we don't need to initialize the mock like mock(ABC.class).
On the other hand #InjectMocks injects the mock automatically with getters and setters. The documentation says:
#InjectMocks currently it only supports setter injection. If you prefer constructor injection - please contribute a patch....
What I don't understand is that when I remove #InjectMocks below I get nullpointer exception for the tests as dependency is null. Does that mean construtor based inject is supported? Or does it has something to do with #RunWith(MockitoJUnitRunner.class)
Here's the code
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
#Mock
private Dependency dependency;
#InjectMocks
private MyClass cls = new MyClass(dependency);
//...
}
class MyClass {
private Dependency dependency;
MyClass(Dependency dependency) {
this.dependency = dependency;
}
//...
}

As of the latest release, Mockito supports constructor injection.
See the latest javadoc.

Related

How to use DependencyInjection in BenchmarkDotNet?

I'd like to use BenchmarkDotNet on some legacy code I'm working with right now. It is written in C# Net462.
It is a big, old and complex system and I'd like to Benchmark some methods inside some specific class. Those classes use dependency injection and I'm not sure how I could do it. All the examples I've seen so far are not using any dependency injection.
Does anyone have any ideas or examples I could have a look?
Thank you very much.
You need to create the dependency injection container in the ctor or a method with [GlobalSetup] attribute, resolve the type that you want to benchmark and store it in a field. Then use it in a benchmark and dispose the DI container in a [GlobalCleanup] method.
Pseudocode:
public class BenchmarksDI
{
private IMyInterface _underTest;
private IDependencyContainer _container;
[GlobalSetup]
public void Setup()
{
_container = CallYourCodeThatBuildsDIContainer();
_underTest = _container.Resolve<IMyInterface>();
}
[Benchmark]
public void MethodA() => _underTest.MethodA();
[GlobalCleanup]
public void Cleanup() => _container.Dispose();
}

What is the purpose of the getter methods in Components in Dagger 2?

I am trying to understand Components in Dagger 2. Here is an example:
#Component(modules = { MyModule.class })
public interface MyComponent {
void inject(InjectionSite injectionSite);
Foo foo();
Bar bar();
}
I understand what the void inject() methods do. But I don't understand what the other Foo foo() getter methods do. What is the purpose of these other methods?
Usage in dependent components
In the context of a hierarchy of dependent components, such as in this example, provision methods such as Foo foo() are for exposing bindings to a dependent component. "Expose" means "make available" or even "publish". Note that the name of the method itself is actually irrelevant. Some programmers choose to name these methods Foo exposeFoo() to make the method name reflect its purpose.
Explanation:
When you write a component in Dagger 2, you group together modules containing #Provides methods. These #Provides methods can be thought of as "bindings" in that they associate an abstraction (e.g., a type) with a concrete way of resolving that type. With that in mind, the Foo foo() methods make the Component able to expose its binding for Foo to dependent components.
Example:
Let's say Foo is an application Singleton and we want to use it as a dependency for instances of DependsOnFoo but inside a component with narrower scope. If we write a naive #Provides method inside one of the modules of MyDependentComponent then we will get a new instance. Instead, we can write this:
#PerFragment
#Component(dependencies = {MyComponent.class }
modules = { MyDependentModule.class })
public class MyDependentComponent {
void inject(MyFragment frag);
}
And the module:
#Module
public class MyDepedentModule {
#Provides
#PerFragment
DependsOnFoo dependsOnFoo(Foo foo) {
return new DependsOnFoo(foo);
}
}
Assume also that the injection site for DependentComponent contains DependsOnFoo:
public class MyFragment extends Fragment {
#Inject DependsOnFoo dependsOnFoo
}
Note that MyDependentComponent only knows about the module MyDependentModule. Through that module, it knows it can provide DependsOnFoo using an instance of Foo, but it doesn't know how to provide Foo by itself. This happens despite MyDependentComponent being a dependent component of MyComponent. The Foo foo() method in MyComponent allows the dependent component MyDependentComponent to use MyComponent's binding for Foo to inject DependsOnFoo. Without this Foo foo() method, the compilation will fail.
Usage to resolve a binding
Let's say we would like to obtain instances of Foo without having to call inject(this). The Foo foo() method inside the component will allow this much the same way you can call getInstance() with Guice's Injector or Castle Windsor's Resolve. The illustration is as below:
public void fooConsumer() {
DaggerMyComponent component = DaggerMyComponent.builder.build();
Foo foo = component.foo();
}
Dagger is a way of wiring up graphs of objects and their dependencies. As an alternative to calling constructors directly, you obtain instances by requesting them from Dagger, or by supplying an object that you'd like to have injected with Dagger-created instances.
Let's make a coffee shop, that depends on a Provider<Coffee> and a CashRegister. Assume that you have those wired up within a module (maybe to LightRoastCoffee and DefaultCashRegister implementations).
public class CoffeeShop {
private final Provider<Coffee> coffeeProvider;
private final CashRegister register;
#Inject
public CoffeeShop(Provider<Coffee> coffeeProvider, CashRegister register) {
this.coffeeProvider = coffeeProvider;
this.register = register;
}
public void serve(Person person) {
cashRegister.takeMoneyFrom(person);
person.accept(coffeeProvider.get());
}
}
Now you need to get an instance of that CoffeeShop, but it only has a two-parameter constructor with its dependencies. So how do you do that? Simple: You tell Dagger to make a factory method available on the Component instance it generates.
#Component(modules = {/* ... */})
public interface CoffeeShopComponent {
CoffeeShop getCoffeeShop();
void inject(CoffeeService serviceToInject); // to be discussed below
}
When you call getCoffeeShop, Dagger creates the Provider<Coffee> to supply LightRoastCoffee, creates the DefaultCashRegister, supplies them to the Coffeeshop constructor, and returns you the result. Congratulations, you are the proud owner of a fully-wired-up coffeeshop.
Now, all of this is an alternative to void injection methods, which take an already-created instance and inject into it:
public class CoffeeService extends SomeFrameworkService {
#Inject CoffeeShop coffeeShop;
#Override public void initialize() {
// Before injection, your coffeeShop field is null.
DaggerCoffeeShopComponent.create().inject(this);
// Dagger inspects CoffeeService at compile time, so at runtime it can reach
// in and set the fields.
}
#Override public void alternativeInitialize() {
// The above is equivalent to this, though:
coffeeShop = DaggerCoffeeShopComponent.create().getCoffeeShop();
}
}
So, there you have it: Two different styles, both of which give you access to fully-injected graphs of objects without listing or caring about exactly which dependencies they need. You can prefer one or the other, or prefer factory methods for the top-level and members injection for Android or Service use-cases, or any other sort of mix and match.
(Note: Beyond their use as entry points into your object graph, no-arg getters known as provision methods are also useful for exposing bindings for component dependencies, as David Rawson describes in the other answer.)

Laravel 5 Facades or Dependency Injection Pros and Cons

I am developing a package for Laravel 5, I decided to benefit form Dependency Injection in my package and it is easy to implement in Laravel particularly for constructor injection, but when it comes to Facades some new issues arise. when we have classes like
class MyController extends \App\Http\Controllers\Controller
{
public $text;
protected $lang;
public function __construct(\Lang $lang)
{
$this->lang = $lang;
}
public function myFunction(){
$this->text = $this->lang->get('package::all.text1');
}
}
The code above doesn't work since the Lang is a Facade, therefore we have to change the code to this:
use Illuminate\Translation\Translator
class MyController extends \App\Http\Controllers\Controller
{
public $text;
protected $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
public function myFunction(){
$this->text = $this->translator->get('package::all.text1');
}
}
The Question:
I need to know what are the advantages and disadvantage of using the facades against using the constructor injection
I also have checked this question:
laravel - dependency injection and the IoC Container and laready asked this question:
Dependency Injection in Laravel 5 Package To Use or Not To Use
you just can help as well with confirming the answer of the first question as well

e4 dependency reinjection order: field vs. method

I was quite surprised to see that there is no deterministic behavior for the order in which objects get reinjected.
public class Test {
#Inject private Boolean testBool;
#Inject
public void checkNewObject(Boolean testBoolNew) {
if (!testBoolNew.equals(this.testBool)) {
System.out.println("Out of sync!");
} else {
System.out.println("In sync!");
}
}
}
And this is how I use the class:
context.set(Boolean.class, new Boolean(true));
Test test = ContextInjectionFactory.make(Test.class, context);
context.set(Boolean.class, new Boolean(false));
So, sometimes I get the output:
In sync!
In sync!
And sometimes I get:
In sync!
Out of sync!
Is this really non deterministic or am I just overseeing something?
The documentation clearly states that the injection order should be:
Constructor injection: the public or protected constructor annotated with #Inject with the greatest number of resolvable arguments is selected
Field injection: values are injected into fields annotated with #Inject and that have a satisfying type
Method injection: values are injected into methods annotated with #Inject and that have satisfying arguments
See: https://wiki.eclipse.org/Eclipse4/RCP/Dependency_Injection#Injection_Order
I'm not sure, why this doesn't work as expected in your case.
How is equals() implemented in MyContent?
Is MyContent annotated with #Creatable and or #Singleton?
As a side note: Is this a practical or just an academic problem? Why is it necessary to inject the same instance into a field and into a method on the same target-instance? If you want to have a field variable to cache the value, you can set this from the method.
If you feel this is a bug, please file it here: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Platform

Using #Inject with generic type

I've been searching here about it, but haven't found an answer.
In my application, I've an abstract main class for my controllers, with some methods and properties. And I want to inject the DAO automatically.
abstract class AbstractController<E extends AbstractEntity, D extends AbstractDAO<E>> {
#Inject
private D dao;
// getters and setters
}
abstract class AbstractDAO<E extends AbstractEntity> {
#PersistentContext
private EntityManager em;
// finds returns E
}
// implemenation/usage
class CarController extends AbstractController<Car, CarDAO> {
}
Getting the exception:
org.jboss.weld.exceptions.DefinitionException: WELD-001407 Cannot declare an injection point with a type variable: [field] #Inject private AbstractController.dao
Using: Glassfish 3.1 and JSF 2.1.
Is there a workaround or alternative for this?
Thanks.
It's technically very complicated for reflection to detect the proper runtime type by a generic declaration in the source and cast to it. Weld simply don't and won't support it.
Better declare it against AbstractDAO<E>:
private AbstractDAO<E> dao;
You gain nothing with declaring it against D anyway.

Resources