I have a Demoiselle 2.4.2 application already running that needs to use SecurityContext
to get the User
currently logged in and make some decisions. The time now is to write the unit tests using JUnit 4 for this application (they were not made in the application genesis, but we want to do it now). At this point the problem arises that there is no logon process that precedes the execution of test cases.
By what technique can you simulate the logon process, so that when instances of SecurityContext
are injected over the controllers of the application in test cases), will these respond to the user I need?
Update 1
To make the situation easier to understand, it follows the code of the class that implements the unit test:
@RunWith(DemoiselleRunner.class)
public class CaixaOperacaoTests {
@Inject
static private Credentials credentials;
@Inject
private CaixaOperacaoBC caixaOperacao;
@Before
public void setUp() throws Exception {
credentials.setUsername("meususario");
credentials.setPassword("minhasenha");
}
@Test
public void shouldAbrirCaixaComUsuarioLogado() {
// Arrange
BigDecimal valorAbertura = new BigDecimal(10.50);
// Act
CaixaSessao sessao = caixaOperacao.abrirCaixa(valorAbertura, null);
// Assert
assertThat(sessao, notNullValue());
}
}
The problem occurs even before the unit test starts, while injecting caixaOperacao
, because this instance depends on the existing credential in an auxiliary class that we call SecurityServices
, which is injected into CaixaOperacaoBC
.
Follow the SecurityServices code:
@ApplicationScoped
public class SecurityServices {
@Inject
SecurityContext securityContext;
@Inject
PessoaBC pessoaBC;
public Long idPessoaFisicaDoUsuarioLogado(){
Long idPessoa = (Long) securityContext.getUser().getAttribute(UsuarioSession.Fields.PESSOA_ID);
return idPessoa;
}
public Pessoa pessoaFisicaDoUsuarioLogado(){
Long idPessoa = idPessoaFisicaDoUsuarioLogado();
return pessoaBC.load(idPessoa);
}
SecurityContext getContext() {
return securityContext;
}
}
Note that in the idPessoaFisicaDoUsuarioLogado()
method there is the use of securityContext
, which has value. However, the getUser()
method returns null
from where all my problems come from.
Of course, the credential definition can not occur in the unit test class, it has to occur before, but where?