Controller层TDD

实现一个 Web Application,对外提供一个获取用户信息的 API,请求 API 时返回用户信息(仅需返回固定的两条用户信息即可,内容如下)

请求样例:

request

curl http://localhost:8080/api/users

response

[{“id”:1,“username”:“Obama”},{“id”:2,“username”:“Clinton”}]

先写测试

@SpringBootTest
@AutoConfigureMockMvc
class SpringOverviewApplicationTests {
    
    

    @Autowired
    private MockMvc mockMvc;

    @Test
    void should_get_ok_when_get_users_api_is_successful() throws Exception {
    
    
        MockHttpServletResponse response = mockMvc
                .perform(MockMvcRequestBuilders.get("/api/users"))
                .andReturn()
                .getResponse();
        assertEquals(200,response.getStatus());
    }

    @Test
    void should_get_users_content_from_users_api() throws Exception {
    
    
        String content = mockMvc
                .perform(MockMvcRequestBuilders.get("api/users"))
                .andReturn()
                .getResponse()
                .getContentAsString();
        User[] users = new ObjectMapper().readValue(content, User[].class);

        assertEquals(2,users.length);
        assertEquals("Obama",users[0].getUsername());
        assertEquals("Clinton",users[1].getUsername());
    }
    @Test
    void should_test_users_api_using_fluent_testing_api() throws Exception {
    
    
        mockMvc.perform(MockMvcRequestBuilders.get("/api/users"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.[0].username", Matchers.is("Obama")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.[1].username",Matchers.is("Clinton")));
    }
}

再写接口

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    
    private List<User> users = Arrays.asList(
            new User(1,"Obama"),
            new User(2,"Clinton")
    );

    @GetMapping
    public List<User> getUsers() {
    
    
        return users;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30738155/article/details/128951365
TDD