我有这个非常简单的控制器类和一个简单的 (jpa) 存储库。我想要做的是测试它的 api 但模拟它的存储库并让它根据测试用例返回或不返回对象。
我现在的问题是我不知道该怎么做。
我知道如何模拟存储库并将其注入控制器/服务类 @Mock / @InjectMocks / when().return()
但是当我在用 MockMvc 发出请求后想做同样的事情时,我失败了。非常感谢任何帮助
控制器
import java.util.Optional;
@RestController
@Slf4j
public class ReceiptController implements ReceiptsApi {
@Autowired
private ReceiptRepository receiptRepository;
@Autowired
private ErrorResponseExceptionFactory exceptionFactory;
@Autowired
private ApiErrorResponseFactory errorResponseFactory;
@Override
public Receipt getReceipt(Long id) {
Optional<ReceiptEntity> result = receiptRepository.findById(id);
if (result.isEmpty()) {
throw invalid("id");
}
ReceiptEntity receipt = result.get();
return Receipt.builder().id(receipt.getId()).purchaseId(receipt.getPurchaseId()).payload(receipt.getHtml()).build();
}
private ErrorResponseException invalid(String paramName) {
return exceptionFactory.errorResponse(
errorResponseFactory.create(HttpStatus.NOT_FOUND.value(), "NOT_VALID", String.format("receipt with id %s not found.", paramName))
);
}
}
而且是测试课
@WebMvcTest(ReceiptController.class)
@RestClientTest
public class ReceiptControllerTest {
@InjectMocks
private ReceiptController receiptController;
@Mock
private ReceiptRepository receiptRepository;
@Mock
private ErrorResponseExceptionFactory exceptionFactory;
@Mock
private ApiErrorResponseFactory errorResponseFactory;
private MockMvc mvc;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(
new ReceiptController())
.build();
}
哈士奇WWW
小怪兽爱吃肉
相关分类