我遵循了本指南,但是使用了kotlin和mysql: https://www.baeldung.com/spring-session-jdbc
我已经设置好了,我的前两个测试通过了,但是我的最后一个(从会话中读取属性)没有通过……这是测试类:
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class SpringSessionJdbcIntegrationTest {
@LocalServerPort
private val port: Int = 0
@Autowired
private val testRestTemplate: TestRestTemplate? = null
private val sessionIdsFromDatabase: List<String>
@Throws(SQLException::class)
get() {
val result = ArrayList<String>()
val rs = getResultSet("SELECT * FROM SPRING_SESSION")
while (rs.next()) {
result.add(rs.getString("SESSION_ID"))
}
return result
}
private val sessionAttributeBytesFromDatabase: List<ByteArray>
@Throws(SQLException::class)
get() {
val result = ArrayList<ByteArray>()
val rs = getResultSet("SELECT * FROM SPRING_SESSION_ATTRIBUTES")
while (rs.next()) {
result.add(rs.getBytes("ATTRIBUTE_BYTES"))
}
return result
}
@Throws(SQLException::class)
private fun getResultSet(sql: String): ResultSet {
val conn = DriverManager.getConnection("jdbc:mysql://mysql.stud.iie.ntnu.no:3306/martwa", "martwa", "PPlgWjdv")
val stat = conn.createStatement()
return stat.executeQuery(sql)
}
@Before
@Throws(ClassNotFoundException::class)
fun setup() {
Class.forName("com.mysql.cj.jdbc.Driver")
}
@Test
@Throws(SQLException::class)
fun givenApiHasStarted_whenMySqlDbIsQueried_thenSessionTablesAreEmpty() {
Assert.assertEquals(0, sessionIdsFromDatabase.size.toLong())
Assert.assertEquals(0, sessionAttributeBytesFromDatabase.size.toLong())
}
@Test
@Throws(SQLException::class)
fun givenGetInvoked_whenMySqlDbIsQueried_thenOneSessionIsCreated() {
assertThat(this.testRestTemplate!!.getForObject("http://localhost:$port/", String::class.java)).isNotEmpty()
Assert.assertEquals(1, sessionIdsFromDatabase.size.toLong())
}
//The third test
@Test
@Throws(ClassNotFoundException::class, SQLException::class, IOException::class)
fun givenPostInvoked_whenMySqlDbIsQueried_thenSessionAttributeIsRetrieved() {
val map = LinkedMultiValueMap<String, String>()
map.add("color", "red")
this.testRestTemplate!!.postForObject("http://localhost:$port/saveColor", map, String::class.java)
val queryResponse = sessionAttributeBytesFromDatabase
Assert.assertEquals(1, queryResponse.size.toLong())
val `in` = ObjectInputStream(ByteArrayInputStream(queryResponse[0]))
val csrfToken = `in`.readObject()
//val header = csrfToken.getHeaderName()
val obj:List<String> = csrfToken as List<String> //Deserialize byte[] to object
Assert.assertEquals("red", obj[0])
}
我得到了错误:
java.lang.ClassCastException:
class org.springframework.security.web.csrf.DefaultCsrfToken cannot be cast to class java.util.List (org.springframework.security.web.csrf.DefaultCsrfToken is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
有谁知道我应该如何从DefaultCsrfToken提取数据,或者知道我应该如何将其转换为List。
我也尝试在Java中执行此操作,但收到相同的错误。