When I write a test code with selenium for the upload screen created with Springboot, The file selection dialog could not be operated and the test could not be performed, so the method to solve it is described below.
Since it is difficult to operate <input type ='file'>
with selenium,
The file is automatically set for the file attribute on the server side (Java side).
Now you don't have to worry about the operation of <input type ='file'>
on selenium side!
ControllerAdviceCustom.java
@ControllerAdvice
public class ControllerAdviceCustom {
@InitBinder
public void initBinderMock(WebDataBinder dataBinder) {
//Mock extension point (implementation uses MockUp on the test side)
}
//Omitted below
}
MockFileEditor.java
public class MockFileEditor extends PropertyEditorSupport {
@Override
public void setValue(Object obj) {
//Generate and reflect MockMultipartFile for parameter (Multipart)
String textFile = "dummy text file";
MultipartFile mockFile = new MockMultipartFile("file", textFile.getBytes());
super.setValue(mockFile);
}
}
SeleniumTest.java
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SeleniumTest {
@Before
public void setup() {
//Implemented mock extension points for ControllerAdviceCustom class
new MockUp<ControllerAdviceCustom>() {
@Mock
@InitBinder
public void initBinderMock(WebDataBinder dataBinder) {
//Set to pass the MockFileEditor class if the type is MultipartFile
dataBinder.registerCustomEditor(MultipartFile.class, new MockFileEditor());
}
};
}
@Test
public void Testing screens including file uploads() {
//Omitted below
}
}
It seems that it is possible to operate <input type ='file'>
even with selenium.
However, it is doubtful whether that method is possible for all browsers, and there is a possibility that it will not be usable due to browser version upgrade (security measures), so I chose this implementation method.
Recommended Posts