48 lines
1.8 KiB
Java
48 lines
1.8 KiB
Java
package com.example.demo.controller;
|
|
|
|
import com.example.demo.service.HelloService;
|
|
import org.junit.jupiter.api.DisplayName;
|
|
import org.junit.jupiter.api.Test;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
|
import org.springframework.http.MediaType;
|
|
import org.springframework.test.web.servlet.MockMvc;
|
|
|
|
import static org.mockito.Mockito.when;
|
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
|
|
@WebMvcTest(HelloController.class)
|
|
@DisplayName("HelloController Unit Tests")
|
|
class HelloControllerTest {
|
|
|
|
@Autowired
|
|
private MockMvc mockMvc;
|
|
|
|
@MockBean
|
|
private HelloService helloService;
|
|
|
|
@Test
|
|
@DisplayName("GET /api/hello returns default greeting")
|
|
void greet_ReturnsDefaultGreeting() throws Exception {
|
|
when(helloService.getGreeting()).thenReturn("Hello, World!");
|
|
|
|
mockMvc.perform(get("/api/hello")
|
|
.accept(MediaType.APPLICATION_JSON))
|
|
.andExpect(status().isOk())
|
|
.andExpect(content().string("Hello, World!"));
|
|
}
|
|
|
|
@Test
|
|
@DisplayName("GET /api/hello/{name} returns personalized greeting")
|
|
void greetWithName_ReturnsPersonalizedGreeting() throws Exception {
|
|
when(helloService.getGreetingFor("Developer")).thenReturn("Hello, Developer!");
|
|
|
|
mockMvc.perform(get("/api/hello/Developer")
|
|
.accept(MediaType.APPLICATION_JSON))
|
|
.andExpect(status().isOk())
|
|
.andExpect(content().string("Hello, Developer!"));
|
|
}
|
|
}
|