How do I inject Ejbs that call other Ejbs into a Junit test class?

Asked

Viewed 172 times

1

I’m trying to test a class in Junit.

Turns out the class I’m testing has several Ejbs that call other Ejbs.

How do I inject into a Junit EJB’s test class called other EJB’s?

Thank you.

1 answer

0

The way I recommend to do a unit test on an EJB is to instantiate the EJB to be tested and mock the Ejbs it calls (i.e., its dependencies). Depending on the form as the EJB is built, you may need to use the method set inject the dependencies or, in the worst case, use some method of Reflection to make the field injection.

For example, see the EJB below:

@Stateless
public class PessoaEjb {

    private final EnderecoEjb enderecoEjb;

    @Inject
    public PessoaEjb(EnderecoEjb enderecoEjb) {
        this.enderecoEjb= enderecoEjb;
    }

    public PessoaEjb () {
        this.enderecoEjb = null;
    }

    public Pessoa validar(Pessoa pessoa) {
        if (pessoa.getNome() == null) {
            return new IllegalArgumentException("Nome inválido");
        }
        enderecoEjb.validar(pessoa.getEndereco());
        return pessoa;
    }
}

A test for him would look something like:

class PessoaEjbTest {

    @Test(expect = IllegalArgumentException.class)
    public void validar() {

        PessoaEjb pessoaEjb = new PessoaEjb(mock(EnderecoEjb.class)); // usei o Mockito aqui
        pessoaEjb.validar(new Pessoa(null));

    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.