使用Spring Boot Test进行错误测试

时间:2017-03-08 09:07:11

标签: java spring-boot junit mockito

我试图在我的服务上实施简单的单元测试。我的测试类的代码如下:

@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存储库。

1 个答案:

答案 0 :(得分:0)

你使用json-smart-v2吗?

在那里你可以看到你的例外中的类存在: Github link

您可能有错误的版本或某些不正确的依赖项。