您可以通过 goggle 获得几个示例 :)。但你可能没想到我会这样回答!
现在冗长但详细的答案请耐心等待:P
您可以使用 junit、mockito、spring test、power-mockito 等进行 JUnitTesting。
我假设您的休息项目结构是:-
1. Controller is :-
@RestController
@RequestMapping("/api")
public class RestApiController {
@Autowired
UserServiceImpl userService;
@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if (users.isEmpty()) {
System.out.println();
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
}
2. Service Layer is :-
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
public List<User> findAllUsers() {
return userDao.findAll();
}
}
}
-
道层:-
和你的一样。
现在对它进行单元测试:-
@RunWith(SpringRunner.class)
@WebMvcTest(value = RestController.class, secure = false)
public class RestControllerTest {
@Autowired
private MockMvc mockMvc;
@SpyBean
private RestApiController restController;
@SpyBean
private UserServiceImpl userService; //Spy will call real method (Use Spy where you want actual execution).
@MockBean
UserDaoImpl userDaoImpl; ( Use Mock where you don't want execution as in your case you don't want to make query in database.) --Use Mock and step 1 define rule which will give expected result without real execution.
// How you will know :- If you place debug and run as debug junit you will find debugger will not go method inside in mocked object)
@Test
public void testListAllUsers(){
List<User> userList= new ArrayList<User>();
userList.add(new User(1, "himanshu", 26, "abc@gmail.com"));
Mockito.when(userDaoImpl.findAll()).thenReturn(userList); //step 1
assertEquals(HttpStatus.OK, restController.listAllUsers().getStatusCode()); // This will check if expected status code is present in response --Happy Case
Assert.assertEquals("himanshu", restController.listAllUsers().getBody().get(0).getName()); // if you also want to test whether object in happy case has valid attribute.
System.out.println(" completed");
}
}
如果您想使用 URL 测试休息呼叫:-
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/api/user/").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(200, result.getResponse().getStatus());
参考链接:-
模拟:https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/Mockito.html
春季测试:- https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html
Maven 依赖:-
春季测试:-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
对于 Mockito 测试:-
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.4</version>
<scope>test</scope>
</dependency>
上面的示例将测试整个 (controller-service-dao) 流程,但是如果您想进行单独的模块测试,这很容易,为此您必须创建 DaoTest 类和模拟 Dao 层并进行类似的测试,这不是一个好方法.
来自 (controller - service -dao) 的测试出现集成测试,它本身会自动测试所有单独的模块。
干杯!!