Search code examples
javajunitserenity-bddthucydides

Spring parametrized JUnit Tests with Serenity


I'm looking for the solution how can i use spring integrations in serenity bdd frameworkk which is using JUnit runner. The issue is that i can't use methods in test data collection method because its static.

I used some answears from that thread but it doesn't work. Maybe i missed something in the explanations. Spring Parameterized/Theories JUnit Tests

@RunWith(SerenityParameterizedRunner.class)
@Concurrent(threads = "5")
public class PlayerTest {

    private Player player;

    public PlayerTest (Player player) {
        this.player = player;
    }

    @Inject
    PlayerService playerService;

    @TestData
    public static Collection<Object[]> testData() {
        return playerService.getPlayers()
                .stream()
                .map(it -> new Object[]{it})
                .collect(Collectors.toList());
    }

    @Steps
    FeedsSteps feedsSteps;

    @Test
    @Title("Check player data")
    public void testPlayer() {
        feedsSteps.checkPlayer(player);
    }

}

Basically everyting looks good but i can't use playerService because testData is static. I'm trying to find some solution how can use methods from my service.


Solution

  • Finally found a solution for my question. The thing is that you need to initialize spring context before collecting test data in static method and than you can inject it. After everyting test will looks like this:

    @RunWith(SerenityParameterizedRunner.class)
    @Concurrent(threads = "5")
    public class PlayerTest {
    
        private Player player;
        private static PlayerService playerService;
    
        public PlayerTest (Player player) {
            this.player = player;
        }
    
        private static synchronized void initBeans() {
            if(context == null)
            {
                context = new AnnotationConfigApplicationContext("com.package.service");
            }
            playerService = context.getBean(PlayerServiceImpl.class);
        }
    
        @TestData
        public static Collection<Object[]> testData() {
            return playerService.getPlayers()
                    .stream()
                    .map(it -> new Object[]{it})
                    .collect(Collectors.toList());
        }
    
        @Steps
        FeedsSteps feedsSteps;
    
        @Test
        @Title("Check player data")
        public void testPlayer() {
            feedsSteps.checkPlayer(player);
        }
    
    }