Implementando teste em Spring-Test com Mock e mais algumas coisas

216 views
Skip to first unread message

Romildo Paiter

unread,
Jan 17, 2014, 10:34:49 AM1/17/14
to tdd-no-m...@googlegroups.com
Ola pessoal tudo bem estou tentando fazer funcionar um Test usando o Spring-Test em um projeto de so String-struts. mas já estou com um erro que esta me deixando maluco... Pois tem é algo que eu quero colocar pra funcionar para criar os novos teste para esse sistema. Mas tbm estou com o tempo escaço.

Codigo.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:**/application-context.xml"})
@WebAppConfiguration("webapp")
@Transactional
// @ContextConfiguration("file:src/main/webapp/WEB-INF/application-context.xml")
// @ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class NotificaEmailServiceTest {
   
   
    private MockMvc mockMvc;

    @Autowired(required=true)
    private NotificacaoEmailService notificacaoEmailServiceMock;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        // notificacaoEmailService = new NotificacaoEmailServiceImpl();
       
        /*mockMvc = MockMvcBuilders.standaloneSetup(new TodoController(messageSource(), todoServiceMock))
                .setHandlerExceptionResolvers(exceptionResolver())
                .setValidator(validator())
                .setViewResolvers(viewResolver())
                .build();*/
       
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();       
    }

    /*@Configuration
    static class ContextConfiguration {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        public NotificacaoEmailService notificacaoEmailService() {
            NotificacaoEmailService orderService = new NotificacaoEmailServiceImpl();
            // set properties, etc.
            return orderService;
        }
    }*/

    @Test
    public void enviaEmailParaArrobaTjmtPontoJusPontoBrTest() {

        notificacaoEmailServiceMock.enviarEmails(TipoNotificacaoEmail.DEFERIMENTO, "texto");

    }

}




Erro...

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gov.tjmt.precatorios.service.NotificaEmailServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private gov.tjpr.precatorios.service.comum.NotificacaoEmailService gov.tjmt.precatorios.service.NotificaEmailServiceTest.notificacaoEmailService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [gov.tjpr.precatorios.service.comum.NotificacaoEmailService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private gov.tjpr.precatorios.service.comum.NotificacaoEmailService gov.tjmt.precatorios.service.NotificaEmailServiceTest.notificacaoEmailService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [gov.tjpr.precatorios.service.comum.NotificacaoEmailService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [gov.tjpr.precatorios.service.comum.NotificacaoEmailService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 28 more


Se alguem souber o que pode ser ficarei muito agradecido.


pom de teste.

<!-- tests -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.2.1</version>
                <scope>test</scope>
            </dependency>
           
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.2.1</version>
                <scope>test</scope>
            </dependency>
           
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-all</artifactId>
                <version>1.3</version>
                <scope>test</scope>
            </dependency>
           
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <artifactId>hamcrest-core</artifactId>
                        <groupId>org.hamcrest</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
           
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>1.9.5</version>
                <scope>test</scope>
            </dependency>
           
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>3.2.4.RELEASE</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>3.2.4.RELEASE</version>
                <scope>test</scope>
            </dependency>
           
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>3.2.4.RELEASE</version>
            </dependency>   
--
--
[]`s
Romildo Jozué Paiter
Bacharelando Sistema da Informação :: UFMT
MCSA: Microsoft Certified
Desenvolvimento de Sistemas e Rede de Computadores.
Fone: (65) 8125-0768


Efraim Gentil

unread,
Jan 17, 2014, 5:10:39 PM1/17/14
to tdd-no-m...@googlegroups.com
O seu bean NotificacaoEmailService está anotado (@Service ) ou configurado via xml para ser injetado ? 




2014/1/17 Romildo Paiter <romild...@gmail.com>

--
Você está recebendo esta mensagem porque se inscreveu no grupo "TDD no mundo real" dos Grupos do Google.
Para cancelar a inscrição neste grupo e parar de receber seus e-mails, envie um e-mail para tdd-no-mundo-r...@googlegroups.com.
Para obter mais opções, acesse https://groups.google.com/groups/opt_out.

Mauricio Aniche

unread,
Jan 22, 2014, 10:42:57 AM1/22/14
to tdd-no-mundo-real
Oi Romildo,

Bem cara de erro de configuração do Spring. Esse bean consegue subir na aplicação?

Um abraço,

Romildo Paiter

unread,
Jan 22, 2014, 11:27:43 AM1/22/14
to tdd-no-m...@googlegroups.com
A aplicação sobe normalmente!!! Estava vendo algumas coisas a mais. Essa aplicação é baseada em Struts e usa o Spring-beans para fazer a injeção. Ainda não desisti de conseguir rodar um teste Mockando a a aplicação.

Mas ta dando muito trabalho pra colocar isso pra funcionar. Também estava vendo  para colar no projeto o StrustsCaseTest. é Bastante interessante a ideia do uso dele, mas ai tive outro problema que foi colocar o contexto do Spring.

Momento em que eu "empaquei" para colocar em funcionamento essa solução!!!

att

Romildo Paiter


2014/1/22 Mauricio Aniche <maurici...@gmail.com>

Mauricio Aniche

unread,
Jan 22, 2014, 11:52:21 AM1/22/14
to tdd-no-mundo-real
É difícil ajudar nesss casos. Vai precisar sofrer um pouco aí com o Spring! :/
2014/1/22 Romildo Paiter <romild...@gmail.com>

Romildo Paiter

unread,
Jan 22, 2014, 11:56:20 AM1/22/14
to tdd-no-m...@googlegroups.com
kkkkkk. Obrigado pelo incentivo!!!
Reply all
Reply to author
Forward
0 new messages