6
respostas

Spring MVC II - Aula 7.4

Registros das tabelas de testes não são apagados, ou seja a cada deploy da erro.

6 respostas

Oi Fernando,

Como está o código da sua classe de teste? Você chegou a criar um profile separado?

Poste aqui o código para darmos uma olhada.

Abraço!

Oi Joviane.

Código ProdutosControllerTeste

import br.com.firstapp.company.conf.AppWebConfiguration;
import br.com.firstapp.company.conf.DataSourceConfigurationTest;
import br.com.firstapp.company.conf.JPAConfiguration;
import br.com.firstapp.company.conf.SecurityConfiguration;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {JPAConfiguration.class, AppWebConfiguration.class, 
    DataSourceConfigurationTest.class, SecurityConfiguration.class})
@ActiveProfiles("test")
public class ProdutosControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Autowired
    private Filter springSecurityFilterChain;

    @Before
    public void setup() {
        //carregar mock
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
                .addFilter(springSecurityFilterChain)
                .build();
    }

    @Test
    public void deveRetornarParaHomeComOsLivros() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(MockMvcResultMatchers
                        .model().attributeExists("produtos"))
                .andExpect(MockMvcResultMatchers
                        .forwardedUrl("/WEB-INF/views/home.jsp"));
    }

    @Test
    public void someneteAdminDeveAcessarProdutosForm() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/produtos/form")
                .with(SecurityMockMvcRequestPostProcessors
                        .user("user@firstapp.com.br").password("123456")
                        .roles("USUARIO")))
                .andExpect(MockMvcResultMatchers.status().is(403));
    }

}

Código JPAConfiguration

import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
public class JPAConfiguration {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setPackagesToScan("br.com.firstapp.company.models");
        factoryBean.setDataSource(dataSource);
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        factoryBean.setJpaProperties(aditionalProperties());
        factoryBean.setJpaVendorAdapter(vendorAdapter);

        return factoryBean;
    }

    private Properties aditionalProperties() {
        //propriedades do hibernate
        Properties props = new Properties();
        // dialeto do hibernate - mysql
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        // mostra e format sql - mysql
        props.setProperty("hibernate.show_sql", "true");
        props.setProperty("hibernate.format_sql", "true");
        // mapeamento DDL - toda mudanca no modelo o hibernate muda o banco
        props.setProperty("hibernate.hbm2ddl.auto", "update");
        return props;
    }

    @Bean
    @Profile("dev")
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("");
        dataSource.setUrl("jdbc:mysql://localhost:3306/firstapp");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

}

Alguém pode me auxiliar?

Oi Fernando,

Na sua classe de DatabaseConfigurationTest você criou uma database diferente da de desenvolvimento?

@Bean
@Profile("test")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(
"jdbc:mysql://localhost:3306/firstapp_test"); 
    dataSource.setUsername("root"); 
    dataSource.setPassword("");
    return dataSource;
}

Esta correto, minha dúvida é o pq, após o teste finalizar os registros não são apagados no BD

public class DataSourceConfigurationTest {

    @Bean
    @Profile("test")
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/firstapp_test");
        dataSource.setUsername("root");
        dataSource.setPassword("");        
        return dataSource;
    }
}