문제

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 ?

도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top