简体   繁体   中英

SpringBoot test service (using repository with JDBCTemplate)

I'm trying to write a test for one of my services. The service uses autowired repository which uses jdbcTemplate to access the DB. The problem is that the test actually puts data in the real DB.
Here is my test class:

@SpringApplicationConfiguration(Application.class)
@SpringBootTest(classes = { UserServiceImpl.class, UserService.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceTest {
@Autowired UserService userService;

@Test
public void test() {
    final String fName = " xxxxxx ";        

    User user = new User();
    user.setFirstName(fName);
    user.setLastName(fName);
    user.setEmail(fName);
    user.setLogin(fName);
    user.setPhone(fName);
    userService.create(user);

    user = userService.getUserByLogin(fName).get();
    assertEquals(fName, user.getLogin());   
 }
}

Is there anything i can do to prevent the userService to work with real DB and somehow just make a simulation?

Best option is to use different DataSource bean in tests. You application would be tested against some in memory DB (typically H2). Just create this test configuration somewhere in your src/test/java/yourRootPackage :

@TestConfiguration
public class DataSourceConfig {

    @Bean
    @Primary
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .generateUniqueName(true)
            .setType(H2)
            .build();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM