如何测试 Spring MVC 和存储库 MongoDb
How to Test Spring MVC along with repository MongoDb
谁能帮我对服务、控制器和存储库进行 junit 测试。我在为服务和控制器编写测试用例时遇到很多错误 class。
这是我的服务class
import com.controller.ValidatorClass;
import com.model.Entity;
import com.model.Status;
import com.repository.Repository;
@Service
public class Service {
@Autowired
private Repository repository;
@Autowired
private SequenceGeneratorService service;
public ResponseEntity storeInDb(ExecutorEntity model) {
ValidatorClass validation = new ValidatorClass();
Map<String, String> objValidate = validation.getInput(model.getLink(), model.getUsername(),
model.getPassword(), model.getSolution());
model.setId(service.getSequenceNumber(Entity.SEQUENCE_NAME));
model.setStatus(Status.READY);
repository.save(model);
return new ResponseEntity(model, HttpStatus.OK);
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public List<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
return ex.getBindingResult()
.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.toList());
}
}
这是我的控制器class
@RestController
@RequestMapping(value = "/create")
public class Controller {
@Autowired
private Service service;
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity code(@Valid @RequestBody Entity model) {
return service.storeInDb(model);
}
我的模型class
@Transient
public static final String SEQUENCE_NAME = "user_sequence";
@NotNull(message = "Name can not be Null")
private String username;
@NotNull(message = "Password can not be Null")
private String password;
@NotNull(message = "Jenkins Link can not be Null")
private String Link;
@NotNull(message = "Solution can not be Null")
private String solution;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private Status status; //enum class having READY and FAIL as values.
以及 getter 和 setter。
JUnit 是一个广泛的主题,您应该仔细阅读:https://junit.org/junit5/
请注意,JUnit 5 是当前版本(我看到您用 junit4
标记了您的问题)。
我将向您介绍如何编写一些集成测试,以帮助您入门。在你的智慧之旅中,你可能会遇到TestRestTemplate
,但现在建议使用WebTestClient
。
下面的测试将使您的应用程序的所有部分都正常运行-运行。当您变得更有经验时,您可能还会测试应用程序的一部分。
package no.yourcompany.yourapp.somepackage;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class ExecutorControllerTest {
@Autowired
WebTestClient webTestClient;
@Test
public void postExecutor_validModel_receiveOk() {
webTestClient
.post().uri("/executor")
.bodyValue(createValidExecutorEntity())
.exchange()
.expectStatus().isOk();
}
@Test
public void postExecutor_validModel_receiveResponseEntity() {
webTestClient
.post().uri("/executor")
.bodyValue(createValidExecutorEntity())
.exchange()
.expectBody(ResponseEntity.class)
.value(responseEntity -> assertThat(responseEntity).isNotNull());
}
private static ExecutorEntity createValidExecutorEntity() {
....
}
}
有了对spring-boot-starter-test
的依赖,就没有必要给JUnit添加明确的依赖了。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
为了使用 WebTestClient
,将以下内容添加到您的 POM:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope>
</dependency>
谁能帮我对服务、控制器和存储库进行 junit 测试。我在为服务和控制器编写测试用例时遇到很多错误 class。
这是我的服务class
import com.controller.ValidatorClass;
import com.model.Entity;
import com.model.Status;
import com.repository.Repository;
@Service
public class Service {
@Autowired
private Repository repository;
@Autowired
private SequenceGeneratorService service;
public ResponseEntity storeInDb(ExecutorEntity model) {
ValidatorClass validation = new ValidatorClass();
Map<String, String> objValidate = validation.getInput(model.getLink(), model.getUsername(),
model.getPassword(), model.getSolution());
model.setId(service.getSequenceNumber(Entity.SEQUENCE_NAME));
model.setStatus(Status.READY);
repository.save(model);
return new ResponseEntity(model, HttpStatus.OK);
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public List<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
return ex.getBindingResult()
.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.toList());
}
}
这是我的控制器class
@RestController
@RequestMapping(value = "/create")
public class Controller {
@Autowired
private Service service;
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity code(@Valid @RequestBody Entity model) {
return service.storeInDb(model);
}
我的模型class
@Transient
public static final String SEQUENCE_NAME = "user_sequence";
@NotNull(message = "Name can not be Null")
private String username;
@NotNull(message = "Password can not be Null")
private String password;
@NotNull(message = "Jenkins Link can not be Null")
private String Link;
@NotNull(message = "Solution can not be Null")
private String solution;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private Status status; //enum class having READY and FAIL as values.
以及 getter 和 setter。
JUnit 是一个广泛的主题,您应该仔细阅读:https://junit.org/junit5/
请注意,JUnit 5 是当前版本(我看到您用 junit4
标记了您的问题)。
我将向您介绍如何编写一些集成测试,以帮助您入门。在你的智慧之旅中,你可能会遇到TestRestTemplate
,但现在建议使用WebTestClient
。
下面的测试将使您的应用程序的所有部分都正常运行-运行。当您变得更有经验时,您可能还会测试应用程序的一部分。
package no.yourcompany.yourapp.somepackage;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class ExecutorControllerTest {
@Autowired
WebTestClient webTestClient;
@Test
public void postExecutor_validModel_receiveOk() {
webTestClient
.post().uri("/executor")
.bodyValue(createValidExecutorEntity())
.exchange()
.expectStatus().isOk();
}
@Test
public void postExecutor_validModel_receiveResponseEntity() {
webTestClient
.post().uri("/executor")
.bodyValue(createValidExecutorEntity())
.exchange()
.expectBody(ResponseEntity.class)
.value(responseEntity -> assertThat(responseEntity).isNotNull());
}
private static ExecutorEntity createValidExecutorEntity() {
....
}
}
有了对spring-boot-starter-test
的依赖,就没有必要给JUnit添加明确的依赖了。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
为了使用 WebTestClient
,将以下内容添加到您的 POM:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope>
</dependency>