Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Erro no teste do Controle usando Heroku e PostgreSQL

Eu adaptei meu projeto para deploy no Heroku usando PostgreSQL. Como a conexão deve ser dinâmica, implementei uma classe Data Source para isso.

A aplicação principal compila e funciona perfeitamente (local e remota), porém não consegui fazer funcionar o teste do Controller, o teste do Repository funciona normalmente.

É possível fazer isso de alguma forma? Procurei bastante mas não encontrei uma solução.

Seguem as classes de teste e o erro ao executar.

AutenticacaoControllerTest:

package br.com.alura.forum.controller;

import java.net.URI;

//import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AutenticacaoControllerTest {

    @Autowired
    private MockMvc mockMvc;

    //@Ignore
    @Test
    public void deveriaDevolver400CasoDadosDeAutenticacaoEstejamIncorretos() throws Exception {
        URI uri = new URI("/auth");
        String json = "{\"email\":\"invalido@email.com\",\"senha\":\"123456\"}";

        mockMvc
        .perform(MockMvcRequestBuilders
                .post(uri)
                .content(json)
                .contentType(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResultMatchers
                .status()
                .is(400));
    }

}

DataSourceConfigTest:

package br.com.alura.forum.config.datasource;

import java.net.URI;
import java.net.URISyntaxException;

import javax.sql.DataSource;

import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile(value = { "prod", "test" })
public class DataSourceConfigTest {

    @Bean    
    public DataSource getDataSource() throws URISyntaxException {

        URI dbUri = new URI(System.getenv("DATABASE_URL"));

        String username = dbUri.getUserInfo().split(":")[0];
        String password = dbUri.getUserInfo().split(":")[1];
        String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

        DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(dbUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();
    }

}

Erro no console:

2021-05-18 15:48:47.708  WARN 5124 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getDataSource' defined in class path resource [br/com/alura/forum/config/datasource/DataSourceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'getDataSource' threw exception; nested exception is java.lang.NullPointerException: Cannot invoke "String.length()" because "this.input" is null
1 resposta
solução!

O problema é que a classe padrão DataSourceConfig estava com o profile de test. Resolvi deixando apenas o profile de prod nessa classe e apaguei a DataSourceConfigTest, já que não seria mais usada, mantendo as configurações de conexão dos testes nos properties.