【发布时间】: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