2

I want to test my controller in Spring-Boot 2.1.3. I want to simulate a POST request. This works quite well but I can't save the data to my Postgres database because H2 can't do JSONB. Therefore I use this library to embed Postgres.

That works quiet well, the database starts but I can't/know how I can bring my mock to save the data in the embedded database.

Do you have any ideas ?

My Test:

@RunWith( SpringRunner.class )
@AutoConfigureMockMvc
@SpringBootTest
public class ControllerTest
{


@InjectMocks
private Student student;

@InjectMocks
private StudentInfo studentinfo;

@Autowired
private MockMvc mockMvc;


@ClassRule
public static PreparedDbRule preparedDbRule = EmbeddedPostgresRules.preparedDatabase( FlywayPreparer.forClasspathLocation( "db/migration" ) );

@Test
public void test() throws Exception
{

    try(EmbeddedPostgres postgres = EmbeddedPostgres.builder.setPort(62239).start();
    Connection connection = postgres.getPostgresDatabase().getConnection()){

    String jsonString = "{"Student" : "name", "course" : "course1"}";

        this.mockMvc.perform( post( "/students" )
                .contentType( MediaType.APPLICATION_JSON )
                .content( jsonString) )
                .andDo( print() )
                .andExpect( status().is( 201 )
                );
    }catch( Exception  e){
        e.printStackTrace();
    }
  }
}

My application.properties:

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:62239/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
flyway.enabled=false

This is not a duplicate question from this, because in this question they used a libary to solve the problem which is only available/compatible in Spring-Boot 1.4.0

upports both Spring and Spring Boot frameworks Supported versions are Spring 4.3.0+ and Spring Boot 1.4.0+

Edit After some testing i found out that i should use an "application.properties" file for my Test. I also set the Port for the Database. But now my I get an random port although i set it with setPort(). I get an random port every start.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
StitZle
  • 89
  • 3
  • 12
  • Possible duplicate of [Embedded Postgres for Spring Boot Tests](https://stackoverflow.com/questions/48956743/embedded-postgres-for-spring-boot-tests) – Andrei Sfat Mar 20 '19 at 17:15
  • in your code have double @InjectMocks, you need to add I guess private Student student as Mock annotation, in order to inject mocks to the InjectMocks, so remove it and try it again. – Jonathan JOhx Mar 20 '19 at 19:26

0 Answers0