Is there any way to implement custom annotations in tests?

Viewed 15

I'm using junit5 and Spring 5 to write tests, like this:

@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
public class UserTests {

    @Autowired
    private UserService userService;

    @Test
    @Sql(statements = { "insert into users (id, name) values (1, 'Joey')" })
    public void test_query_user_by_id() {
        User user = userService.queryById(1L);
        Assertions.assertNotNull(user);
    }

}

Notice that I'm using @Sql to add a user before running the test. That's convenient but it requires me to write SQL directly. I don't want to write SQL, I want to call a service method UserService#addUser to do that. It would be great if I can call it just by adding a custom annotation @AddUser, like this:

@Test
@AddUser(id = 1, name = 'Joey') // it will call UserService#addUser for me
public void test_query_user_by_id() {
    User user = userService.queryById(1L);
    Assertions.assertNotNull(user);
}

Is it possible? If it is, where can I implement @AddUsers's logic?

0 Answers
Related