我在运行单元测试用例时遇到JUnit问题。我正在使用JUnit5。我不知道为什么在运行测试代码时会遇到此异常。我尝试了所有可能的方法来执行代码,但是我无法运行测试用例。
***************************
APPLICATION FAILED TO START
***************************
Description:
Field eventMapperRepository in com.tdchannels.sdk.ms.channel.service.impl.EventServiceImpl required a bean of type 'com.tdchannels.sdk.ms.channel.repository.EventMapperRepository' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.tdchannels.sdk.ms.channel.repository.EventMapperRepository' in your configuration.
2020/10/09 16:33:06.617 [Test worker] ERROR o.s.test.context.TestContextManager - Request-id : - Caught exception while allowing TestExecutionListener [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@64fbf401] to prepare test instance [com.tdchannels.sdk.ms.channel.controllers.PaymentChannelControllerV1Test@5cb2e16b]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:95)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342)
这是我的控制人
@Validated
@RestController
@RequestMapping(path = "/v1/sdk/s2s")
@Slf4j
public class PaymentChannelControllerV1 {
@Autowired
S2SService s2SService;
@PostMapping("/payment")
public ResponseDto createPaymentRequestConversation(@RequestHeader(name = ApplicationConstant.CHANNEL_ID, required = false) String channelId,
@RequestHeader(name = ApplicationConstant.SERVER_ID, required = false) String serverId,
@Valid @RequestBody(required = false) Map<String, @Valid RequestDetails> paymentRequestCo) {
if (CollectionUtils.isEmpty(paymentRequestCo)) return s2SService.getServerHandshakeResponse(serverId);
RequestDetails requestDetails = (RequestDetails) paymentRequestCo.values().toArray()[0];
String widgetId = (String) paymentRequestCo.keySet().toArray()[0];
log.info("Payment create request for user : {} : {}", widgetId, requestDetails);
return s2SService.savePaymentRequestDetails(widgetId, channelId, requestDetails);
}
}
这是我的服务类Method
@Override
public ResponseDto savePaymentRequestDetails(String widgetId, String channelId, RequestDetails requestDetails) {
String userId = requestDetails.getCustomerHash();
String sdkAccountId = requestDetails.getAccountId();
log.info("Payment create request for user {} passed : Request Timestamp - {}", userId, requestDetails.getPaymentInitDate());
log.info("sdkAccountId : {}, channelId : {}, userId : {}", sdkAccountId, channelId, userId);
UserChannel userChannel = getUserChannelFromPassedParams(sdkAccountId, channelId, userId);
if (Objects.isNull(userChannel)) {
log.info("User channel not found. Going to initialize user");
initializeSdkUser(sdkAccountId, userId);
userChannel = getUserChannelFromPassedParams(sdkAccountId, channelId, userId);
}
storeDataInConversation(userChannel, requestDetails, widgetId);
return new SuccessResponseDto("Success");
}
这是我的请求详细信息类
@NoArgsConstructor
@AllArgsConstructor
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RequestDetails {
@NotNull
private String accountId;
private String message;
@NotNull
private String customerHash;
private String requester;
@JsonProperty("vpa")
private String requesterVpa;
@JsonProperty("txnAmount")
private String transactionAmount;
private String formattedAmount;
private String programId;
private Long paymentInitDate;
private Long paymentExpiryDate;
@NotNull
private String requestId;
private String detailPageDeeplink;
private String detailPageDeeplinkApp;
private String detailPageDeeplinkPwa;
// private Map<String, PaymentRequestState> states = RequestState.descriptionRequestStateMap;
private List<ClickThroughAction> cta;
private List<Action> action;
private Map<String, String> additionalParams;
private Long transactionDate;
private StatePojo currentState;
private String title;
private String description;
private String merchantId;
private String terminalId;
private String channel;
private String tranId;
@JsonProperty("event_type")
private String eventType;
}
她是我的测试用例
@SpringBootTest(properties = {"spring.profiles.active=test"},webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@EnableAutoConfiguration(exclude = {CouchbaseReactiveDataAutoConfiguration.class,
CouchbaseReactiveRepositoriesAutoConfiguration.class, DataSourceAutoConfiguration.class,
CouchbaseDataAutoConfiguration.class, CouchbaseAutoConfiguration.class,
CouchbaseRepositoriesAutoConfiguration.class})
public class PaymentChannelControllerV1Test {
@Autowired
MockMvc mockMvc;
@Autowired
S2SService s2SService;
@MockBean
UserChannelRepository userChannelRepository;
@MockBean
WidgetRepository widgetTemplateRepository;
@MockBean
S2sServerAccountRepository s2sServerAccountRepository;
@MockBean
RestTemplate restTemplate;
@MockBean
UserProfileRepository userProfileRepository;
@Autowired
@Qualifier("restTemplateWithoutLB")
RestTemplate restTemplateReal;
@Test
void testCreatePaymentRequestConversation_success() throws Exception {
Mockito.when(userChannelRepository.findById(Mockito.anyString())).thenReturn(Optional.of(new UserChannel()));
WidgetTemplate widgetTemplate = new WidgetTemplate();
widgetTemplate.setWidgetType("merchantpay");
widgetTemplate.setRequester("");
widgetTemplate.setEncryptedKeys(Stream.of("requester", "requesterVpa").collect(Collectors.toList()));
Mockito.when(widgetTemplateRepository.findById(Mockito.anyString()))
.thenReturn(Optional.of(widgetTemplate));
IntegratorUserProfile integratorUserProfile = new IntegratorUserProfile();
integratorUserProfile.setEncryptionKey("asdfghjklasdfghj");
integratorUserProfile.setInitVector("asdfghjklasdfghj");
Mockito.when(userProfileRepository.findById(Mockito.anyString()))
.thenReturn(Optional.of(integratorUserProfile));
mockMvc.perform(
MockMvcRequestBuilders.post("/v1/sdk/s2s/payment").content(TestConstants.PAYMENT_REQUEST_SUCCESS).headers(new HttpHeaders())
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.status").value(1));
}
}
这是我的礼物
plugins {
id 'org.springframework.boot' version '2.2.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'jacoco'
}
jacoco {
toolVersion = "0.8.5" //jacoco version
}
jacocoTestReport {
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it, include: 'com/tdchannels/sdk/**')
})
}
reports {
xml.enabled true
html.enabled true
csv.enabled true
}
}
group = 'com.tdchannels'
version = '2.0.0'
sourceCompatibility = '1.8'
task printVersion {
print project.version
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-couchbase'
// compile group: 'com.microsoft.azure', name: 'applicationinsights-web-auto', version: '2.5.0'
implementation group: 'com.microsoft.azure', name: 'applicationinsights-spring-boot-starter', version: '2.6.0'
implementation group: 'com.microsoft.azure', name: 'applicationinsights-logging-logback', version: '2.6.0'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation group: 'org.modelmapper', name: 'modelmapper', version: '2.3.8'
implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-config', version: '2.2.2.RELEASE'
implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-netflix-eureka-client', version: '2.2.2.RELEASE'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '2.2.2.RELEASE'
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
compileOnly 'org.projectlombok:lombok:1.18.4'
//Version library
compile group: 'com.github.zafarkhaja', name: 'java-semver', version: '0.9.0'
annotationProcessor 'org.projectlombok:lombok:1.18.4'
// implementation 'org.springframework.boot:spring-boot-starter-actuator'
// testImplementation('org.junit.platform:junit-platform-launcher:1.2.0')
}
test {
useJUnitPlatform()
}