4

I am wondering how i am doing tests with CDI. and mocking classes during injection.

if i have the class:

@Named
@RequestScoped
public class ItemProcessor {

  @Inject
  private ItemDao itemDao;


  public void execute() {


    List<Item> items = itemDao.fetchItems();
    for (Item item : items) {
        System.out.println("Found item " + item);
    }
  }
}

How do i do if i want to mock the ItemDao class during test, when i want to test My ItemProcessor ?

Trind
  • 1,583
  • 4
  • 18
  • 38

2 Answers2

4

Frameworks, like mockito, can set dependencies to mocks even when using field injection: http://docs.mockito.googlecode.com/hg/latest/org/mockito/InjectMocks.html

In general, however, constructor injection is preferred for this exact reason: testability.

rethab
  • 7,170
  • 29
  • 46
2

You could - for example - use CDI "Alternatives".

@Alternative
public class TestCoderImpl implements Coder { ... }

Now, this bean will only be used if it is declared in your beans.xml as an alternative.

<alternatives>
    <class>package.TestCoderImpl</class>
</alternatives>

Further info.

Csaba
  • 965
  • 9
  • 20
  • Can i have my normal bean without the @Alternative annotation and just do the during test? – Trind May 24 '13 at 08:51
  • 1
    Sure, your normal bean wouldn't have the @Alternative annotation, your test bean would have it. You could activate your alternative bean by placing the mentioned tag in your beans.xml. – Csaba May 24 '13 at 08:57
  • Is it possible todo the samething on just a @Produce method? – Trind May 24 '13 at 09:36
  • 1
    Well, you could create a bean in your producer method based on a condition, see [here](http://docs.oracle.com/javaee/6/tutorial/doc/gkgkv.html). Or, there is a more advanced solution [here](http://marcus-schulte.blogspot.hu/2012/12/globally-configurable-wiring.html). – Csaba May 24 '13 at 09:46