CDI testing, mocking bean

I am wondering how I do tests with CDI. and mocking classes during injections.

if I have a 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 can I do it if I want to mock the ItemDao class during the test, when I want to check My ItemProcessor?

+4
source share
2 answers

You could, for example, use the CDI "Alternatives".

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

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

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

Further information .

+2
source

Frames like mockito can set dependencies for bullying 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. Possibility of testing.

+4
source

Source: https://habr.com/ru/post/1482525/


All Articles