test(backend): add failing tests for step 10 — AuthService and AuthController

This commit is contained in:
2026-03-26 19:03:35 -03:00
parent 731c80a2bc
commit 9065db504e
2 changed files with 138 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
package com.condado.newsletter.controller
import com.condado.newsletter.scheduler.EntityScheduler
import com.condado.newsletter.service.JwtService
import com.ninjasquad.springmockk.MockkBean
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.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import jakarta.servlet.http.Cookie
@SpringBootTest
@AutoConfigureMockMvc
class AuthControllerTest {
@Autowired
lateinit var mockMvc: MockMvc
@Autowired
lateinit var jwtService: JwtService
@MockkBean
lateinit var entityScheduler: EntityScheduler
@Test
fun should_return200AndSetCookie_when_correctPasswordPosted() {
mockMvc.perform(
post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("""{"password":"testpassword"}""")
)
.andExpect(status().isOk)
.andExpect(cookie().exists("jwt"))
.andExpect(cookie().httpOnly("jwt", true))
}
@Test
fun should_return401_when_wrongPasswordPosted() {
mockMvc.perform(
post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("""{"password":"wrongpassword"}""")
)
.andExpect(status().isUnauthorized)
}
@Test
fun should_return200_when_getMeWithValidCookie() {
val token = jwtService.generateToken()
mockMvc.perform(
get("/api/auth/me")
.cookie(Cookie("jwt", token))
)
.andExpect(status().isOk)
}
@Test
fun should_return401_when_getMeWithNoCookie() {
mockMvc.perform(get("/api/auth/me"))
.andExpect(status().isUnauthorized)
}
@Test
fun should_return401_when_protectedEndpointAccessedWithoutCookie() {
mockMvc.perform(get("/api/v1/virtual-entities"))
.andExpect(status().isUnauthorized)
}
}