【问题标题】:Cannot instantiate @InjectMocks field无法实例化 @InjectMocks 字段
【发布时间】:2019-12-04 10:34:30
【问题描述】:

我已经创建了一个用于登录 log4j 的包装器,它扩展了 HandlerInterceptorAdapter 保持构建类型的 maven 项目。我在我的 Spring Boot 应用程序中将此项目用作外部 JAR。在我的控制器中使用 Logger。我已经为它编写了运行良好但在 mvn 安装期间出现异常的 JUnit。

DemoLogger 是一个向日志公开函数的接口。 DemoLogger 是 maven 项目的一部分,它是一个外部 jar。

控制器

@RestController @RequestMapping("/api/v1")
public class DemoController {

    private DemoLogger logger = LoggerFactory.createLog(DemoController.class);

    @GetMapping("/demo")
    public ResponseEntity<String> getString() {
        logger.info("This is test debug");
        return new ResponseEntity("Hello World", HttpStatus.OK);
    }
}

JUnit

public class DemoControllerTest {

    @InjectMocks private DemoController demoController;

    @Before public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test public void shouldReturnString()throws Exception {
        final String body = demoController.getString().getBody().toString();
        assertEquals("Hello World", body);
    }
}

错误日志

Cannot instantiate @InjectMocks field named 'demoController' of type 'class dev.example.controller.DemoController'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : dev/example2/logger/factory/LoggerFactory

at dev.example.controller.DemoControllerTest.setup(DemoControllerTest.java:18)
Caused by: java.lang.NoClassDefFoundError: dev/example2/logger/factory/LoggerFactory

【问题讨论】:

  • 在测试类中使用@RunWith(MockitoJUnitRunner.class)。

标签: java spring-boot junit mockito log4j


【解决方案1】:

这似乎更像是一个 Mockito 的 Maven 问题。

您很可能在使用该 jar 时没有在 pom 中将其指定为依赖项。

它可以在您的本地 IDE 中工作,因为很可能您手动将它添加到类路径中。

尝试将该 jar 安装在您的本地 .m2 中(或者理想情况下安装在您公司的 Nexus 或类似的东西上),然后运行构建:

mvn install:install-file

更多信息here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多