我开始学习单元测试,我已经浏览过许多博客,这些博客都在寻找信息以使用Spring Gradle开发用于REST API的单元测试,但最后总是会引发一些不同的错误(不推荐使用的库方法,null点等)。 如果您能为我提供一个具体的例子或帮助我使这一工作按预期进行,我将不胜感激 春季启动版本是2.1.0
这是我的模特
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Data;
/**
* User
*/
@Data
@Entity
public class User {
private @Id @GeneratedValue Long id;
private String userId;
private String password;
private int role;
public User() {
}
public User(String userId, String password, int role) {
this.userId = userId;
this.password = password;
this.role = role;
}
}
存储库
public interface UserRepository extends JpaRepository<User, Long> {
}
控制器
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.stream.Collectors;
import com.v1.portal.model.User;
import com.v1.portal.repository.UserRepository;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* UserController
*/
@RestController
public class UserController {
private final UserRepository repository;
private final UserResourceAssembler assembler;
public UserController(UserRepository repository, UserResourceAssembler assembler) {
this.repository = repository;
this.assembler = assembler;
}
@GetMapping("/v1/users")
public Resources<Resource<User>> getAll() {
List<Resource<User>> users = repository.findAll().stream().map(assembler::toResource).collect(Collectors.toList());
return new Resources<>(users, linkTo(methodOn(UserController.class).getAll()).withSelfRel());
}
@PostMapping("/v1/users")
public ResponseEntity<?> add(@RequestBody User user) throws URISyntaxException {
Resource<User> resource = assembler.toResource(repository.save(user));
return ResponseEntity.created(new URI(resource.getId().expand().getHref())).body(resource);
}
@GetMapping("/v1/users/{id}")
public Resource<User> getById(@PathVariable Long id) {
User user = repository.findById(id).orElseThrow(() -> new UserNotFoundException(id));
return assembler.toResource(user);
}
@PutMapping("/v1/users/{id}")
public ResponseEntity<?> update(@RequestBody User newUser, @PathVariable Long id) throws URISyntaxException {
User updatedUser = repository.findById(id).map(user -> {
user.setUserId(newUser.getUserId());
user.setPassword(newUser.getPassword());
user.setRole(newUser.getRole());
return repository.save(user);
}).orElseGet(() -> {
newUser.setId(id);
return repository.save(newUser);
});
Resource<User> resource = assembler.toResource(updatedUser);
return ResponseEntity.created(new URI(resource.getId().expand().getHref())).body(resource);
}
@DeleteMapping("/v1/users/{id}")
public ResponseEntity<?> delete(@PathVariable Long id) {
repository.deleteById(id);
return ResponseEntity.noContent().build();
}
public boolean exists(User user) {
return getById(user.getId()) != null;
}
}
这是带有可能不需要的库的测试部分
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.v1.portal.controller.UserController;
import com.v1.portal.model.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
// import static org.hamcrest.Matchers.containsString;
// import static org.hamcrest.Matchers.hasSize;
// import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
String url = "http://localhost:7888/v1/users";
MockMvc mockMvc;
@Autowired
UserController userController;
@Test
public void contextLoads() {
User user = new User("Test", "Test", 0);
ObjectMapper mapper = new ObjectMapper();
try {
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(user);
System.out.println("JSON = " + json);
// mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8).content(json)).andExpect(status().isOk());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// userController.newUser(json);
}
@Test
public void test_create_user_success() throws Exception {
User user = new User("Arya Stark", "pawd", 0);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(user);
when(userController.exists(user)).thenReturn(false); // fails from here on
doNothing().when(userController).add(user);
mockMvc.perform(post(url).contentType(MediaType.APPLICATION_JSON).content(json)).andExpect(status().isCreated());
verify(userController, times(1)).exists(user);
verify(userController, times(1)).add(user);
verifyNoMoreInteractions(userController);
}
}
预先感谢,对当前代码的任何建议对提高我的能力都将非常有帮助