Skip to content

Commit

Permalink
test Code 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
dennis0405 committed Jan 16, 2025
1 parent 1ac6071 commit 47015bd
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ class ReservationControllerTest {

val updateRequestBody = """
{
"roomId": ${room.id},
"startDate": "2023-12-01",
"endDate": "2024-01-05",
"numberOfGuests": 2
Expand Down Expand Up @@ -114,7 +113,6 @@ class ReservationControllerTest {
// 다른 유저가 예약 수정 시 403 반환
val updateRequestBody = """
{
"roomId": ${room.id},
"startDate": "2023-12-01",
"endDate": "2024-01-05",
"numberOfGuests": 2
Expand Down Expand Up @@ -188,7 +186,6 @@ class ReservationControllerTest {
println(responseContent)
}

// 예약 생성을 2개할때, 중복이 되면 exception 처리가 되는지 확인하는 테스트코드를 작성
@Test
fun `예약 생성시 기간이 겹치면 409 응답을 반환한다`() {
val (user, token) = dataGenerator.generateUserAndToken()
Expand Down Expand Up @@ -341,7 +338,7 @@ class ReservationControllerTest {
val rootNode: JsonNode = objectMapper.readTree(jsonString)
val contentNode: JsonNode = rootNode.path("content")
return if (contentNode.isArray && contentNode.size() > n) {
contentNode[n].path("id").asLong()
contentNode[n].path("reservationId").asLong()
} else {
null
}
Expand All @@ -358,4 +355,4 @@ class ReservationControllerTest {
fun setUp() {
dataGenerator.clearAll()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.status().isCreated)
.andReturn()
} finally {
latch.countDown()
Expand All @@ -90,7 +90,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.status().isConflict)
.andReturn()
} finally {
latch.countDown()
Expand Down Expand Up @@ -133,7 +133,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token1")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.status().isCreated)
.andReturn()
} finally {
latch.countDown()
Expand All @@ -149,7 +149,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token2")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isBadRequest)
.andExpect(MockMvcResultMatchers.status().isConflict)
.andReturn()
} finally {
latch.countDown()
Expand Down Expand Up @@ -203,7 +203,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token1")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.status().isCreated)
.andReturn()
} finally {
latch.countDown()
Expand All @@ -219,7 +219,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token2")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.status().isCreated)
.andReturn()
} finally {
latch.countDown()
Expand All @@ -232,8 +232,6 @@ class ReservationIntegrationTest {
assertEquals(2, reservations.size)
}

// 기간이 5.10 ~ 5.15 5.12 ~ 5.17로 이렇게 겹치는 경우에 대해서도 테스트코드 작성해줘
// 5.10 ~ 5.15 5.12 ~ 5.17로 겹치는 경우에 대해서는 5.10~5.15 건만 예약 성공해야함
@Test
fun `should not allow overlapping reservations`() {
val (user1, token1) = dataGenerator.generateUserAndToken()
Expand Down Expand Up @@ -275,7 +273,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token1")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.status().isCreated)
.andReturn()
} finally {
latch.countDown()
Expand All @@ -291,7 +289,7 @@ class ReservationIntegrationTest {
.header("Authorization", "Bearer $token2")
)
.andDo(MockMvcResultHandlers.print()) // 요청/응답 로깅
.andExpect(MockMvcResultMatchers.status().isBadRequest)
.andExpect(MockMvcResultMatchers.status().isConflict)
.andReturn()
} finally {
latch.countDown()
Expand All @@ -303,4 +301,4 @@ class ReservationIntegrationTest {
val reservations = reservationRepository.findAll()
assertEquals(1, reservations.size)
}
}
}
49 changes: 28 additions & 21 deletions src/test/kotlin/com/example/toyTeam6Airbnb/RoomConcurrencyTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors

Expand All @@ -34,17 +34,17 @@ class RoomConcurrencyTest {
}

@Test
fun `동일한 요청이 2개들어오면 방 하나만 만들어야함(멱등성)`() {
fun `should throw DuplicateRoomException when two identical requests are made concurrently`() {
val (user, token) = dataGenerator.generateUserAndToken()

val latch = CountDownLatch(2)
val executor = Executors.newFixedThreadPool(2)

val requestBody = """
{
"name": "Cozy Apartment in Seoul",
"roomName": "Cozy Apartment in Seoul",
"description": "A beautiful and cozy apartment located in the heart of Seoul. Perfect for travelers!",
"type": "APARTMENT",
"roomType": "APARTMENT",
"address": {
"sido": "Seoul",
"sigungu": "Jongno-gu",
Expand All @@ -63,13 +63,14 @@ class RoomConcurrencyTest {
"price": {
"perNight": 5000,
"cleaningFee": 5000,
"charge": 5000,
"total": 0
"charge": 5000
},
"maxOccupancy": 1
}
""".trimIndent()

val results = mutableListOf<Int>()

executor.submit {
try {
val result = mockMvc.perform(
Expand All @@ -78,9 +79,9 @@ class RoomConcurrencyTest {
.content(requestBody)
.header("Authorization", "Bearer $token")
)
.andDo(MockMvcResultHandlers.print()) // Log request/response
.andExpect(MockMvcResultMatchers.status().isOk)
.andDo(MockMvcResultHandlers.print())
.andReturn()
results.add(result.response.status)
} finally {
latch.countDown()
}
Expand All @@ -94,23 +95,25 @@ class RoomConcurrencyTest {
.content(requestBody)
.header("Authorization", "Bearer $token")
)
.andDo(MockMvcResultHandlers.print()) // Log request/response
.andExpect(MockMvcResultMatchers.status().isOk)
.andDo(MockMvcResultHandlers.print())
.andReturn()
results.add(result.response.status)
} finally {
latch.countDown()
}
}

latch.await()

assertEquals(1, results.count { it == HttpStatus.CREATED.value() })
assertEquals(1, results.count { it == HttpStatus.CONFLICT.value() })

val rooms = roomRepository.findAll()
assertEquals(1, rooms.size)
}

// requestBody를 위와 같은 형태로 하여 서로 다른 유저가 같은 방을 만드는 동시성 상황에 대한 테스트 케이스 형성
@Test
fun `동일한 요청이 서로 다른 유저로부터 들어오면 방이 하나만 만들어져야함`() {
fun `should throw DuplicateRoomException when identical requests are made by different users concurrently`() {
val (user1, token1) = dataGenerator.generateUserAndToken()
val (user2, token2) = dataGenerator.generateUserAndToken()

Expand All @@ -119,9 +122,9 @@ class RoomConcurrencyTest {

val requestBody = """
{
"name": "Cozy Apartment in Seoul",
"roomName": "Cozy Apartment in Seoul",
"description": "A beautiful and cozy apartment located in the heart of Seoul. Perfect for travelers!",
"type": "APARTMENT",
"roomType": "APARTMENT",
"address": {
"sido": "Seoul",
"sigungu": "Jongno-gu",
Expand All @@ -140,13 +143,14 @@ class RoomConcurrencyTest {
"price": {
"perNight": 50000,
"cleaningFee": 20000,
"charge": 5000,
"total": 0
"charge": 5000
},
"maxOccupancy": 4
}
""".trimIndent()

val results = mutableListOf<Int>()

executor.submit {
try {
val result = mockMvc.perform(
Expand All @@ -155,9 +159,9 @@ class RoomConcurrencyTest {
.content(requestBody)
.header("Authorization", "Bearer $token1")
)
.andDo(MockMvcResultHandlers.print()) // Log request/response
.andExpect(MockMvcResultMatchers.status().isOk)
.andDo(MockMvcResultHandlers.print())
.andReturn()
results.add(result.response.status)
} finally {
latch.countDown()
}
Expand All @@ -171,17 +175,20 @@ class RoomConcurrencyTest {
.content(requestBody)
.header("Authorization", "Bearer $token2")
)
.andDo(MockMvcResultHandlers.print()) // Log request/response
.andExpect(MockMvcResultMatchers.status().isOk)
.andDo(MockMvcResultHandlers.print())
.andReturn()
results.add(result.response.status)
} finally {
latch.countDown()
}
}

latch.await()

assertEquals(1, results.count { it == HttpStatus.CREATED.value() })
assertEquals(1, results.count { it == HttpStatus.CONFLICT.value() })

val rooms = roomRepository.findAll()
assertEquals(1, rooms.size)
}
}
}
30 changes: 15 additions & 15 deletions src/test/kotlin/com/example/toyTeam6Airbnb/RoomControllerTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ class RoomControllerTest {

val requestBody = """
{
"name": "Sample Room",
"roomName": "Sample Room",
"description": "A beautiful and cozy apartment located in the heart of Seoul. Perfect for travelers!",
"type": "APARTMENT",
"roomType": "APARTMENT",
"address": {
"sido": "Seoul",
"sigungu": "Jongno-gu",
Expand Down Expand Up @@ -84,9 +84,9 @@ class RoomControllerTest {
// create a room with mockmvc
val requestBody = """
{
"name": "Sample Room_2",
"roomName": "Sample Room_2",
"description": "A nice place to stay",
"type": "VILLA",
"roomType": "VILLA",
"address": {
"sido": "Seoul",
"sigungu": "Gangnam",
Expand Down Expand Up @@ -124,7 +124,7 @@ class RoomControllerTest {

// extract room id from create_result's body
val responseBody = create_result.contentAsString
val roomId = responseBody.split("\"id\":")[1].split(",")[0].toLong()
val roomId = responseBody.split("\"roomId\":")[1].split(",")[0].toLong()

// room should be accessible without authentication
val result = mockMvc.perform(
Expand Down Expand Up @@ -173,7 +173,7 @@ class RoomControllerTest {
val rootNode: JsonNode = objectMapper.readTree(jsonString)
val contentNode: JsonNode = rootNode.path("content")
return if (contentNode.isArray && contentNode.size() > n) {
contentNode[n].path("id").asLong()
contentNode[n].path("roomId").asLong()
} else {
null
}
Expand All @@ -193,9 +193,9 @@ class RoomControllerTest {

val requestBody = """
{
"name": "Sample Room",
"roomName": "Sample Room",
"description": "A beautiful and cozy apartment located in the heart of Seoul. Perfect for travelers!",
"type": "APARTMENT",
"roomType": "APARTMENT",
"address": {
"sido": "Seoul",
"sigungu": "Jongno-gu",
Expand Down Expand Up @@ -233,13 +233,13 @@ class RoomControllerTest {
// Add assertions to verify the response content if needed
println(responseContent)

val roomId = responseContent.split("\"id\":")[1].split(",")[0].toLong()
val roomId = responseContent.split("\"roomId\":")[1].split(",")[0].toLong()

val updateRequestBody = """
{
"name": "Sample Room_2",
"roomName": "Sample Room_2",
"description": "A nice place to stay",
"type": "VILLA",
"roomType": "VILLA",
"address": {
"sido": "Seoul",
"sigungu": "Gangnam",
Expand Down Expand Up @@ -296,9 +296,9 @@ class RoomControllerTest {

val requestBody = """
{
"name": "Sample Room",
"roomName": "Sample Room",
"description": "A beautiful and cozy apartment located in the heart of Seoul. Perfect for travelers!",
"type": "APARTMENT",
"roomType": "APARTMENT",
"address": {
"sido": "Seoul",
"sigungu": "Jongno-gu",
Expand Down Expand Up @@ -337,7 +337,7 @@ class RoomControllerTest {
// Add assertions to verify the response content if needed
println(responseContent)

val roomId = responseContent.split("\"id\":")[1].split(",")[0].toLong()
val roomId = responseContent.split("\"roomId\":")[1].split(",")[0].toLong()

// verify 403 forbidden for user 2
val deleteResult2 = mockMvc.perform(
Expand Down Expand Up @@ -379,7 +379,7 @@ class RoomControllerTest {

val result = mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/rooms/main/search")
.param("name", "Room1")
.param("roomName", "Room1")
.param("page", "0")
.param("size", "10")
.accept(MediaType.APPLICATION_JSON)
Expand Down

0 comments on commit 47015bd

Please sign in to comment.