0

I am trying to write a self-contained integration test for my Spring Boot application.

The Test class is like this:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Sql("/create_schema.sql")
public class UserControllerTest {
    @LocalServerPort
    private int port;

    private String baseUrl = "http://localhost";


    private static RestTemplate restTemplate = null;

    @BeforeAll
    public static void init() {
        restTemplate = new RestTemplate();
    }

    @BeforeEach
    public void setUp() {
        baseUrl = baseUrl.concat(":").concat(port+ "").concat("/users");
    }


    @Test
    @Sql("/create.sql")
    public void test1() {
        User user = restTemplate.getForObject(baseUrl.concat("/users/{username}"), User.class, "username1");

        Assertions.assertNotNull(user);
        Assertions.assertEquals(100L, user.getId());
    }
}

The create_schema.sql file is like this:

CREATE TABLE USERINFO
(
    USER_ID NUMBER(19,0) NOT NULL,
    PWD VARCHAR2(255 CHAR),
    USERNAME VARCHAR2(255 CHAR),
    PRIMARY KEY (USER_ID)
);

The create.sql file just insert one line of data:

INSERT INTO USERINFO (USER_ID, USERNAME, PWD) VALUES(100, 'username1','$2y$12$iUHx4NGJpgJKskDhhN12y.e/D9tzHe/B7DbDOf37Pfx0xDymIazpi');

When I run the test. The error I was given is

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "USERINFO" not found; SQL statement:
INSERT INTO USERINFO (USER_ID, USERNAME, PWD) VALUES(100, 'username1','$2y$12$iUHx4NGJpgJKskDhhN12y.e/D9tzHe/B7DbDOf37Pfx0xDymIazpi') [42102-200]

This is very strange because the create_schema.sql runs fine and a table USERINFO should be created in H2.

In my IDE (IntelliJ), the

USERINFO (USER_ID, USERNAME, PWD) 

in the INSERT statement is shown as red and the IDE says "Unable to resolve table USERINFO".

What did I do wrong?

1
  • can you show the complete exception with stack trace ? Commented May 5, 2021 at 2:15

1 Answer 1

0

Use @SqlMergeMode(MergeMode.MERGE) at class level to merge the sql queries and run them both. It seems like your class level SQL annotation is overridden by method level SQL annotation. Hence the create schema sql is never executed.

For further reading please refer: https://www.concretepage.com/spring-5/sql-example-spring-test

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.