以下是我尝试执行测试用例时遇到的错误。它说预计至少有 1 个 bean 有资格作为 autowire 候选者。下面给出了完整的错误日志和 java 类。
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Results :
Tests in error:
ProductServiceTests.testContractService400Response » IllegalState Failed to lo...
ProductServiceTests.testContractService500Response » IllegalState Failed to lo...
ProductServiceTests.testInvalidRequestCancelDateFormat » IllegalState Failed t...
Tests run: 3, Failures: 0, Errors: 3, Skipped: 0
下面给出的是java代码。ProductServiceTests.java
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import com.cnanational.productservice.controller.ProductServiceController;
public class ProductServiceTests extends ProductServiceApplicationTests{
@Value(ProductServiceController.PATH_GET_SURCHARGES)
protected String productSurcharges;
@Override
public MockHttpServletRequestBuilder failureTestsRequestBuilder() throws Exception {
String requestJson = rawJsonFromFile(
"com/cnanational/productservice/service/valid-request.json");
System.out.println("the value of surcharges = "+ this.restProperties);
return post("/surcharges")
.header(HttpHeaders.AUTHORIZATION, validBasicAuthHeaderValue())
.header(this.restProperties.getHeaders().getRemoteUser(), USER_NAME)
.content(requestJson)
.contentType(MediaType.APPLICATION_JSON);
}
@Test
public void testInvalidRequestCancelDateFormat() throws Exception
{
String requestJson = rawJsonFromFile(
"com/cnanational/productservice/service/valid-request.json");
System.out.println("the value of basicAuthHeaderValue111="+ validBasicAuthHeaderValue());
System.out.println("the value of surcharges = "+ this.restProperties);
this.mvc.perform(post("/surcharges")
.header(HttpHeaders.AUTHORIZATION, validBasicAuthHeaderValue())
.header(this.restProperties.getHeaders().getRemoteUser(), USER_NAME)
.content(requestJson)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.status", equalTo(400)))
.andExpect(jsonPath("$.fields", Matchers.hasSize(2)))
.andExpect(jsonPath("$.fields[?(@.name == 'cancelDate' && @.code == 'ValidDate')]").exists())
.andExpect(jsonPath("$.fields[?(@.name == 'cancelMiles' && @.code == 'Max')]").exists())
.andDo(MockMvcResultHandlers.print());
}
}
----------------------
package com.cnanational.productservice;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Consumer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.cnanational.productservice.controller.ProductServiceController;
import com.cnanational.servicecommon.config.CommonRestProperties;
import com.cnanational.servicecommon.util.RestUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
@EnableWebMvc
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ProductServiceApplication.class,
properties = {
"spring.config.location=classpath:product-service/",
"spring.config.name=product-service",
"logging.config=classpath:logback-test.xml"
})
@AutoConfigureMockMvc
@ActiveProfiles(value = ProductServiceApplication.PROFILE_TEST)
public abstract class ProductServiceApplicationTests
{
@Autowired
protected ProductServiceController controller;
@Autowired
protected MockMvc mvc;
@Autowired
protected CommonRestProperties restProperties;
@Autowired
protected ObjectMapper objectMapper;
@MockBean
protected RestTemplate restTemplate;
@Value("${security.user.name}")
protected String username;
@Value("${security.user.password}")
protected String password;
protected static final String USER_NAME = "web_jdoe";
protected String validBasicAuthHeaderValue()
{
return RestUtils.createBasicAuthString(
username,
password);
}
public abstract MockHttpServletRequestBuilder failureTestsRequestBuilder()
throws Exception;
/**
* Asserts that an upstream 400 response is returned to the client.
*
* @throws Exception
*/
@Test
public void testContractService400Response() throws Exception
{
MockHttpServletRequestBuilder failureTestsRequestBuilder = failureTestsRequestBuilder();
if (failureTestsRequestBuilder == null)
{
return;
}
String mockedJson = rawJsonFromFile("com/cnanational/productservice/service/invalid-response-400.json");
ResponseEntity<String> mockedResponse = ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(mockedJson);
given(this.restTemplate.exchange(any(), eq(String.class)))
.willReturn(mockedResponse);
this.mvc.perform(failureTestsRequestBuilder)
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.status", equalTo(400)))
.andExpect(jsonPath("$.code", equalTo(3000)));
}
/**
* Asserts that an upstream 500 response is returned to the client.
*
* @throws Exception
*/
@Test
public void testContractService500Response() throws Exception
{
MockHttpServletRequestBuilder failureTestsRequestBuilder = failureTestsRequestBuilder();
if (failureTestsRequestBuilder == null)
{
return;
}
String mockedJson = rawJsonFromFile("com/cnanational/productservice/service/invalid-response-500.json");
ResponseEntity<String> mockedResponse = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(mockedJson);
given(this.restTemplate.exchange(any(), eq(String.class)))
.willReturn(mockedResponse);
this.mvc.perform(failureTestsRequestBuilder)
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.status", equalTo(500)))
.andExpect(jsonPath("$.code", equalTo(800004)));
}
@SuppressWarnings("unchecked")
protected <T> ResponseEntity<T> mockResponseEntityFromFile(String path, Class<T> responseBodyClass) throws Exception
{
String responseJson = rawJsonFromFile(path);
T responseBody = null;
if (String.class.equals(responseBodyClass))
{
responseBody = (T) responseJson;
}
else
{
responseBody = this.objectMapper.readValue(
responseJson,
responseBodyClass);
}
ResponseEntity<T> mockedResponse = ResponseEntity.ok(responseBody);
return mockedResponse;
}
protected void testForMultipleStringValues(
Consumer<UrlWithVariables> function,
UrlWithVariables ... urlsWithVariables) throws Exception
{
for (UrlWithVariables urlWithVariables : urlsWithVariables)
{
try
{
function.accept(urlWithVariables);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
/**
* Retrieves JSON from a file on the classpath.
*
* @param path
* @return
* @throws Exception
*/
protected String rawJsonFromFile(String path) throws Exception
{
System.out.println(path);
URI uri = getClass().getClassLoader().getResource(path).toURI();
return new String(Files.readAllBytes(Paths.get(uri)));
}
public static class UrlWithVariables
{
private String url;
private Object[] variables;
public UrlWithVariables(String url, Object ... variables)
{
this.url = url;
this.variables = variables;
}
public String getUrl()
{
return url;
}
public Object[] getVariables()
{
return variables;
}
}
public static void rethrowException(Action action)
{
try
{
action.execute();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static interface Action
{
public void execute() throws Exception;
}
public static class FieldNameCodePair
{
private String fieldName;
private String code;
public FieldNameCodePair(String fieldName, String code)
{
this.fieldName = fieldName;
this.code = code;
}
public static FieldNameCodePair from(final String fieldName, final String code)
{
return new FieldNameCodePair(fieldName, code);
}
public String getFieldName()
{
return fieldName;
}
public void setFieldName(String fieldName)
{
this.fieldName = fieldName;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
}
}
如果需要任何其他代码库,我会将它们添加到问题中。任何输入表示赞赏。谢谢。