无法实例化@InjectMocks 字段

Cannot instantiate @InjectMocks field

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

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

这看起来更像是 Mockito 的 Maven 问题。

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

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

尝试将该 jar 安装到您本地的 .m2(或者最好是在您公司的 Nexus 或类似的东西上),然后 运行 构建:

mvn install:install-file

更多信息here