【发布时间】:2017-07-28 18:28:41
【问题描述】:
我正在尝试对我的服务进行简单的单元测试。我的测试类的代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Mock
private UserRepository userRepoMock;
private UserService userService;
private List<User> users;
@Before
public void setUp() throws Exception {
userService = new UserService(userRepoMock);
User u1 = new User();
u1.setEmail("test@test.com");
User u2 = new User();
u2.setEmail("test2@test.com");
users = Arrays.asList(u1, u2);
}
@Test
public void getAll() throws Exception {
when(userRepoMock.findAll()).thenReturn(users);
List<UserDTO> all = userService.getAll(new PageRequest(0, 20));
verify(userRepoMock).findAll();
}
}
执行测试时,我总是遇到异常,这是摘录:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
...
Caused by: java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
...
Caused by: java.lang.ClassNotFoundException: net.minidev.json.writer.JsonReaderI
...
我的代码有什么问题?我是否应该包含一些 spring-boot-starter-test 中未包含的依赖项?
注意我正在使用 Spring Boot v 1.5.1 和 Spring Data MongoDB 存储库。
【问题讨论】:
-
您的应用程序是否正常启动,或者您是否也遇到同样的错误?为您的依赖项使用 Maven 或 Gradle?
-
@WimDeblauwe 我正在使用 Maven,是的,我的应用程序正在正确启动...
-
您可能想使用 Maven
dependency:tree命令查看是否包含所需的依赖项。请参阅maven.apache.org/plugins/maven-dependency-plugin/tree-mojo.html 您是从 Maven 还是从 IDE 运行测试?如果来自您的 IDE,您是否确保导入了最新的 pom.xml 更改? -
@WimDeblauwe 我发现我的项目中存在依赖冲突:
spring-boot-starter-test需要 json-smart v2.2.1 和另一个使用 v 1.3 的库 (nimbus-jose-jwt)。这导致了问题... -
根据 json-smart 2.2.1 和 1.3 之间的兼容性,您将需要添加排除项或尝试获取也适用于 json-smart 2.2 的更新版本的 nimbus-jose-jwt .1.
标签: java spring-boot junit mockito