Search code examples
javaspringspring-bootselenium-webdriverspring-boot-test

How can I manipulate the data in Spring Boot Test class so that it is updated on the Server as well? (Integration testing, Selenium)


I want to make an integration Selenium test of my Spring Boot Web application, however I can't figure out how to update the object inside my test class, so that the server would use the updated version of it.

Basically, the question is how to connect the object "ad" with the same object on the server side?

@DirtiesContext
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = Application.class)
public class IntegrationTest {
    // this field I want to update during the testing, so that the server knows about it
    @Autowired
    AppData ad;
    @Autowired
    AppLogic logic;
    @LocalServerPort
    int port;

    private WebDriver driver;
    private ChromeOptions options;

    @BeforeEach
    public void setUp() throws InterruptedException {
        // SpringApplication.run(Application.class);

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
        options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        options.setBinary("D:\\chrome.exe");
    }

    public void test() {
        // loading the browser and connecting to the server
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://localhost:8081");

        // here I want to rig and manipulate the data, which the server is using ("ad" object),
        // but the problem is it does not affect it on the server side
        ad.getPlayers();
        ad.setCards("rigged data");
    }
}
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@Controller
public class AppController {
    AppLogic logic;
    AppData ad;

    public AppController(AppLogic logic, AppData ad) {
        this.logic = logic;
        this.ad = ad;
    }

    // ...
}
@Component
public class AppLogic {
    // ...
}
public interface AppData {
    // ...
}
@Component
public class AppDataImpl implements AppData {
    ...
}

Solution

  • So I've figured out it was just a silly mistake, I should have used a @LocalServerPort field in order to connect to the server, which is:

    @LocalServerPort
    int port;
    

    So connecting to the server should take the following form:

    driver.get("http://localhost:" + port);
    

    This way all necessary data are injected properly, so that we can manipulate it in our tests.