Я хочу протестировать свой уровень контроллера, поэтому я использовал аннотацию @WebMvcTest, потому что я не хочу запускать весь сервер. Но когда я запускал тест контроллера, тест всегда терпел неудачу. Мой код ControllerTest выглядит следующим образом:
@RunWith(SpringRunner.class)
@WebMvcTest(value = ServiceController.class)
public class ServiceControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@MockBean
private CloudServiceFacade cloudServiceFacade;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void checkRoleExist() throws Exception {
}
}
Фрагмент сообщений об ошибках, например:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisPoolConfig' defined in class path resource [tools.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxTotal'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxTotal}"
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:563)
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:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 28 more
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxTotal'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxTotal}"
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:596)
at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:603)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:216)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1497)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1237)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
... 42 more
Caused by: java.lang.NumberFormatException: For input string: "${redis.maxTotal}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.valueOf(Integer.java:766)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:208)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:468)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:441)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:199)
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:576)
... 48 more
Я могу понять сообщение об ошибке, потому что в моем приложении (я использую SpringBoot) у меня есть класс Bootstrap, который является входом в приложение. Класс Bootstrap выглядит следующим образом:
@SpringBootApplication(scanBasePackages = {"com.netease.permission"})
@ImportResource("classpath:applicationContext.xml")
public class Bootstrap {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class);
}
}
Он импортирует внешний xml: applicationContext.xml и applicationContext.xml ниже:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="database.xml" />
<import resource="tools.xml" />
<import resource="dubbo-service.xml" />
<import resource="spring-mvc.xml" />
</beans>
Проблема в том, что я не хочу импортировать весь applicationContext.xml, потому что он определяет всю зависимость дополнительных ресурсов, например mysql\redis\zk и т. д. но только spring-mvc.xml. Потому что в spring-mvc.xml я определяю перехватчики. Я хочу протестировать перехватчики и контроллер в моем ServiceControllerTest.
Я уже добавил @TestConfiguration("classpath:spring-mvc.xml"), указывающий, что я хочу только импортировать конфигурацию spring-mvc.xml, но это не работает.
Кто-нибудь сталкивался с моей ситуацией, может ли кто-нибудь помочь?