这是我提供的服务:
@Service
public class UserInfoService {
@Autowired
private UserInfoServiceClient UserInfoServiceClient; // Call another Rest API
public ResponseEntity<ResponseUserInfoData> sendUserInfo(String UserId) throws RuntimeException {
ResponseUserInfoData responseUserInfoData = new ResponseUserInfoData();
//Get the body from the User service client
UserServiceDTO UserServiceDTO = UserInfoServiceClient.sendResponse(UserId).getBody();
//Set the values of responseUserInfoData
Optional<UserServiceDTO> UserServiceDTOOptional = Optional.ofNullable(UserServiceDTO);
if (UserServiceDTOOptional.isPresent()) {
UserServiceDTOOptional.map(UserServiceDTO::getId).ifPresent(responseUserInfoData::setid);
}
else return ResponseEntity.noContent().build();
}
}
我必须测试一下。我是JUnit测试的新手。我要测试以下几点:
要检查服务是否返回响应实体
检查get和set方法是否有效
这是我开始的?
@RunWith(MockitoJUnitRunner.class)
public class ServiceTests {
@InjectMocks
private UserInfoService UserInfoService;
@Mock
private UserInfoServiceClient UserInfoServiceClient;
@Mock
private UserServiceDTO UserServiceDTO;
@Test
public void shouldReturnUserInfoData() throws IOException{
UserInfoService.sendUserInfo("ABC");
}
}
有什么帮助吗?
答案 0 :(得分:1)
Mockito用于模拟服务的依赖关系,以便您可以测试服务中的所有代码路径。在您的情况下,您需要对serInfoServiceClient.sendResponse(UserId)的调用进行存根,并使其针对每个测试用例返回特定的UserServiceDTO。
测试文件看起来设置正确,您只需要模拟该方法即可为特定测试提供所需的结果,例如
@RunWith(MockitoJUnitRunner.class)
public class ServiceTests {
@InjectMocks
private UserInfoService UserInfoService;
@Mock
private UserInfoServiceClient UserInfoServiceClient;
@Test
public void shouldReturnUserInfoData() throws IOException{
final String userId = "123";
// The mocked return value should be set up per test scenario
final UserServiceDto dto = new UserServiceDto();
final ResponseEntity<UserServiceDTO> mockedResp = new ResponseEntity<>(dto, HttpStatus.OK);
// set up the mock service to return your response
when(UserInfoServiceClient.sendResponse(userId)).thenReturn(mockedResp);
// Call your service
ResponseEntity<ResponseUserInfoData> resp = UserInfoService.sendUserInfo(userId);
// Test the result
Assert.isNotNull(resp);
}
}
还有其他方法可以使用Mockito模拟依赖关系。我建议快速开始https://site.mockito.org/