Wednesday, September 14, 2011

Mock/Stub do EntityManager no Spring Roo

Problema

Ao tentar criar testes de unidade para o método persist de uma classe criada pelo Spring Roo, tentei utilizar um Stub para o EntityManager da seguinte forma:



public class ClasseATest {
    @Test
    public void aoPersistirDeveriaChamarClasseB() throws Exception {
        
        Mockery contexto = new Mockery();
        final ClasseB classeB = contexto.mock(ClasseB.class);
        
        final ClasseA classeA = 
            new ClasseA(getEntityManagerStub(), classeB);

        contexto.checking(new Expectations() {{
            one(classeB).fazerAlgo(classeA);

        }
    });
        classeA.persist();
        
        contexto.assertIsSatisfied();
    }

    private EntityManager getEntityManagerStub() {
        return new EntityManager() {
            ...
        }
    }
}
Código da ClasseA

public class ClasseA {
...

    public ClasseA(EntityManager entityManager, ClasseB classeB) {
        this.entityManager = entityManager;
        this.classeB = classeB;
    }



    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
     
        this.entityManager.persist(this);
     
        classeB.fazerAlgo(this);
     
    }

...
 }


O teste funcionava quando era executado dentro de Eclipse, mas falhava quando era executado via maven, no momento da execução do mvn jetty:run-exploded.


Motivo

Provavelmente o spring roo está injetando o EntityManager logo após a chamada ao constructor.

Solução

Utilizar setter injection, como mostrado abaixo:


public class ClasseATest {
    @Test
    public void aoPersistirDeveriaChamarClasseB() throws Exception {
        
        Mockery contexto = new Mockery();
        final ClasseB classeB = contexto.mock(ClasseB.class);
        
        final ClasseA classeA =
            new ClasseA(classeB);
        classeA.setEntityManager(getEntityManagerStub());
        
        contexto.checking(new Expectations() {{
            one(classeB).fazerAlgo(classeA);

        }
    });
        classeA.persist();
        
        contexto.assertIsSatisfied();
    }

    private EntityManager getEntityManagerStub() {

        return new EntityManager() {
            ...
        }

    }
}


Código da ClasseA


public class ClasseA {
...

    public ClasseA(ClasseB classeB) {
        this.classeB = classeB;
    }


    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }




    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
      
        this.entityManager.persist(this);
      
        classeB.fazerAlgo(this);
      
    }

...
 }


Provavelmente deve existir uma solução mais elegante, que permita a utilização da injeção da dependência no construtor. Quando tiver tempo vou pesquisar e bloggar a solução.






Wednesday, June 15, 2011

Keep CMD Open

Problem

The cmd window close after finish the execution of a bat file. The desired behavior is that the cmd stay opened to the input of new comands.

Reason

It is the default behavior.

Solution

  • Create a bat file that will call another bat. Ex: keppCmdOpen.bat
  • In the file put the line: start "" fileWithCommands.bat /k
  • Create the file fileWithCommands.bat and add the desired commands.

Others

If the need is just to see the window, and not to input commands, there is no need to two bats. Just put the pause command at the end of the file.

More info:

http://answers.yahoo.com/question/index?qid=20090306121738AAkg8Ij
http://pt.w3support.net/index.php?db=so&id=905352

Manter cmd aberto

Problema

A janela do cmd se fecha ao final da execução das instruções em um arquivo bat. O comportamento desejado é que o cmd permaneça aberto para a entrada de novos comandos.

Motivo

Este é o comportamento padrão.

Solução

  • Crie um arquivo bat que irá chamar outro. Por exemplo: manterCmdAberto.bat
  • No arquivo criado adicione a seguinte linha: start "" arquivoComComandos.bat /k
  • Crie o arquivo arquivoComComandos.bat e adicione os comando desejados.
Outros

Se o que se deseja é apenas visualizar o conteúdo da janela cmd, e não entrar com comandos, não precisa dos dois arquivos. Simplesmente no segundo arquivo (arquivoComComandos.bat) adicione a linha: pause

Mais informações nos seguinte links:



Saturday, June 11, 2011

Spring Roo GWT application works in dev mode but not in production

Problem

A spring roo gwt application works in dev mode (mvn gwt:run) but not works in production mode (mvn tomcat:run or mvn jetty:run). When trying the late it shows a page with a rectangle with the message loading inside.

Reason

Solution

Assuming that the project is the sample that comes with roo expenses.roo. In STS (Spring Source Tool Suite):

  • Edit the project properties
  • Select Deployment Assembly
  • Click Add
  • Select Folder
  • Select target/extrack-0.1.0.BUILD-SNAPSHOT (or whatever your version is)
  • Click Finish
  • Right click on the project or the pom.xml
  • Select Run As -> Maven assembly:assembly
  • App should re-deploy to the server

This solution was originally posted here: http://forum.springsource.org/showthread.php?106292-Problem-with-expenses.roo-sample-and-STS-2.6.0

Aplicação Spring Roo GWT funciona em modo de desenvolvimento, mas não em produção

Problema

Uma aplicação spring roo configurada para utilizar o gwt funciona em modo de desenvolvimento (mvn gwt:run), mas não funciona quando se faz o deploy em produção (mvn tomcat:run ou mvn jetty:run). Quando se tenta o último mostra uma página com um quadrado e dentro a mensagem loading.

Motivo

Solução

Assumindo que o projeto é o sample que vem com o spring roo (expenses.roo). No STS (Spring Source Tool Suite):
  • Vá nas propriedades do projeto.
  • Selecione Deployment Assembly.
  • Clique em adicionar.
  • Selecione folder.
  • Selecione target/extrack-0.1.0.BUILD-SNAPSHOT.
  • Clique em finalizar.
  • Selecione Run As -> Maven assembly:assembly.


Atualização em 25 ago 2011

Por algum motivo os passos acima não estavam funcionando. Talvez tenha sido pela atualização do STS. Os passos abaixo resolveram o problema:

  • Retire o diretório target/extrack-0.1.0.BUILD-SNAPSHOT do Deployment Assembly como tinha feito acima.
  • Execute o comando mvn jetty:run-exploded.

Compilation error without editing source files in spring roo project

Problem

With no editing of source files from a spring roo project compilation errors appears. This errors are in the source controlled by roo (the aspects).


Sem que se tenha editado o código fonte de um projeto spring roo, problemas de compilação apareceram. Este problemas são na parte que o o roo controla e não devemos editar (Os aspectos).

Reason

Using a different version (older) of roo to work with the project that was created with a newer version of roo. I think it is a problem of roo. It should not allow to open a new projet with an old version of roo.

Solution

Revert the sources to the previous version. It is trivial if you are using a version control.

Erro de compilação em projeto spring roo sem ter editado arquivos

Problema

Sem que se tenha editado o código fonte de um projeto spring roo, problemas de compilação apareceram. Este problemas são na parte que o o roo controla e não devemos editar (Os aspectos).

Motivo

Utilizar o roo numa versão diferente (no caso mais antiga) da versão que foi utilizada para a criação do projeto. O próprio roo deveria verificar isto e nãom permitir abrir o projeto.

Solução

Voltar o código fonte a versão anterior. Trivial com a utilização de controle de versão.