当前位置: 首页 > 知识库问答 >
问题:

抛出WebServerException:无法使用Powermock和Springboot启动嵌入式Tomcat

梅安平
2023-03-14

我用的是Springboot和junit,我想用Powermock来模拟静态类,添加了Powermock后,单元测试通过IntelliJ IDEA运行得很好,但是当我在terminal下运行MVN test时,它会抛出ApplicationContextException:无法启动web服务器\n无法启动嵌入式Tomcat

我的基本测试类:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@RunWith(PowerMockRunner.class)
@PowerMockIgnore( {"javax.management.*", "javax.net.*", "javax.crypto.*"})
@Slf4j
@ComponentScan(basePackages = {"com.rolls"})
@ActiveProfiles("test")
@Transactional
@Rollback
public class ApplicationTest {
    ...test
}

测试类:

@Slf4j
@PrepareForTest(ClientCache.class)
public class RuleServiceTest extends ApplicationTest {


    @Mock
    private IClient iClient;

    @Before
    public void setUp() {
        PowerMockito.mockStatic(ClientCache.class);
    }

    ...test
}
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
    </parent>
        <!--   mock class    -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
[INFO] --- maven-surefire-plugin:3.0.0-M4:test (default-test) @ dq-web ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.rolls.ApplicationTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 36.015 s - in com.rolls.ApplicationTest
[INFO] Running com.rolls.common.utils.DateUtilTest
[ERROR] Tests run: 3, Failures: 0, Errors: 3, Skipped: 0, Time elapsed: 18.619 s <<< FAILURE! - in com.rolls.common.utils.DateUtilTest
[ERROR] com.rolls.common.utils.DateUtilTest.testGetFormattedDate1  Time elapsed: 0.618 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@5b6afa58]
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@5b6afa58]
Caused by: java.lang.Error: factory already defined
...
[ERROR] com.rolls.service.impl.RuleServiceTest.testListNotIn  Time elapsed: 0.001 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@795c941b]
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@795c941b]
Caused by: java.lang.Error: factory already defined

似乎@runwith(powermockrunner.class)无法启动springboot嵌入的tomcat,但要使用Powermock,我需要使用它运行。

问:有人知道如何将Powermock与SpringBoot集成吗?

共有1个答案

申屠宗清
2023-03-14

解决方案:我改为使用Mockito 3.4.6而不是PowerMock

请参见下面的伪代码:

我要测试的目标方法

public String paramReplace(String type) {
   ...code here
   IClient client = ClientCache.getClient(type);
   client.execute();
   ...code here
}
public ClientCache {
   public static getClient(String type) {
      ...code here
      return client;
   } 
}
public Client {
   public String execute() {
     ...code here
     return "a";
   }
}
@Slf4j
public class JobParamReplaceTest extends ApplicationTest {

    @Autowired
    public JobParamReplace jobParamReplace;
    @Mock
    private IClient iClient;
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.openMocks(this);
//        PowerMockito.mockStatic(ClientCache.class);
       
//        iClient = Mockito.mock(IClient.class);
        MockedStatic<ClientCache> clientCache = Mockito.mockStatic(ClientCache.class);
        clientCache.when(() -> ClientCache.getClient(Mockito.anyInt())).thenReturn(iClient);
//        Mockito.when(iClient.executeQuery(Mockito.any(ISourceDTO.class), Mockito.any(SqlQueryDTO.class))).thenReturn(new ArrayList<Map<String, Object>>());
        Mockito.when(iClient.executeQuery(Mockito.any(ISourceDTO.class), Mockito.any(SqlQueryDTO.class))).thenReturn(new ArrayList(1));
    }

    @Test
    public void testParamReplace() throws Exception {
        String sql_res = jobParamReplace.paramReplace("a");
        Assert.assertTrue(StringUtils.isNotBlank(sql_res));
    }
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class)
@RunWith(SpringRunner.class)
@Slf4j
@ComponentScan(basePackages = {"com.dtstack"})
@ActiveProfiles("test")
@Transactional
@Rollback
public class ApplicationTest {

}
<dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.4.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
            <scope>test</scope>
        </dependency>
 类似资料:
  • 说明:无法启动web服务器;嵌套的异常是org。springframework。靴子网状物服务器WebServerException:无法启动嵌入式Tomcat 启动Tomcat上下文时出错。例外情况: 组织。springframework。豆。工厂BeanCreationException。消息:创建在类路径资源[org/springframework/boot/actuate/autoconf

  • 我有时会在pom中看到以下声明。xml。。。 如您所见,sping-boo-starter-web被声明为tomcat-embed-jasper。 是不是sping-boo-starter-web已经有一个嵌入式tomcat了?为什么一些开发人员仍然声明tomcat-embed-jasper以及boot-starter-web?还是有什么原因?

  • 我刚开始使用Spring Boot,在运行我的应用程序时出现了错误。我正在学习教程,我相信我有正确的父母和依赖与POM,请帮助我 主类: POM:

  • 我正在学习《行动中的Spring》第四版第5章,但是我被第一个例子困住了。 以下是我的Eclipse Luna项目结构: 如果我将此项目作为Spring Boot应用程序运行,则会引发异常: 我怎样才能解决这个问题? 所有文件的内容: 随地吐痰。爪哇: SpittrWebAppInitializer.java: 网络配置。爪哇: RootConfig。爪哇: HomeController.java

  • 我是Spring的新手,所以我从Spring intializr下载了jar for maven-web java 1.8 demo。我将其提取并导入STS以运行main()文件,我得到了以下异常。有人能告诉我有什么解决方案吗? 我从Web尝试但不起作用的解决方案:-尝试将Hibernate验证器依赖项添加到pom-尝试将spring-boot-starter-tomcat依赖项添加到pom 堆栈