0
votes

I'm using Spring Boot and Spring Data Rest to expose my Data repository.

The integration test I wrote, adds a user to the database and then calls the rest method to lists users. But the added user is NOT being listed.

An ApplicationRunner is used to populate the DB with data and I'm using Spring profiles for differnt databases.

For example, for my tests:

spring:
  profiles: unittest
  datasource:
    url: 'jdbc:h2:mem:MYDB;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE'
    driver-class-name: org.h2.Driver
    username: myname
    password: mypassword
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: create-drop
  jpa:
    hibernate:
      dialect: org.hibernate.dialect.H2Dialect

The unit test:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("unittest")
@AutoConfigureTestEntityManager
@Transactional
public class MyUserRepoIntegrationTest {
  private static Logger log = Logger.getLogger(MyUserRepoIntegrationTest.class);
  // 3 default users + "test"
  private static final int NUM_USERS = 4;

  @Autowired
  private TestRestTemplate restTemplate;
  @Autowired
  private TestEntityManager entityManager;

  @Before
  public void setupTests() {
    entityManager.persistAndFlush(new MyUser("test", "test"));
  }

  @Test
  public void listUsers() {
    ResponseEntity<String> response = restTemplate.withBasicAuth("user", "user").getForEntity("/apiv1/data/users", String.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getBody()).contains("\"totalElements\" : "+NUM_USERS);
  }
}

The last assertion always fails. There are only 3 users in the DB, the ones added by the ApplicationRunner (via the userRepository). I've tried using the userRepository instead of the TestEntityManager and adding the user inside the test method itself, but nothing changes.

I've verified, that it's using H2 and not my production DB.

EDIT:

Upon closer inspection, the Data actually gets to the Database. When I inject my UserRepository and call .count(), it gives me NUM_USERS (4).

The Problem probably lies with Spring Data REST, since the REST response doesn't include the new user. I've also tried modifying an existing user and explicitly calling flush(), yet the response is still the same. I've removed 'spring-boot-starter-cache' from my POM and added spring.cache.type=none to my application.yml for the 'unittest' profile, but no luck.

1
Have you tried to move the user adding in the test method rather than setup method ?davidxxx
Yes, as written in my second to last sentence.Benjamin Maurer

1 Answers

0
votes

I'm using the UserRepository to add the data now and have removed the TestEntityManager entirely. It works now...