java - Spring Boot 单元测试

标签 java junit spring-boot

我是 spring boot 的新手。需要一些建议 这是我的单元测试类

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class EmployeeRepositoryTest {

@Autowired
protected EmployeeRepository employeeRepository;


@Test
public void insertEmploee(){

    Employee employee = new Employee();

    employee.setEmpName("Azad");
    employee.setEmpDesignation("Engg");
    employee.setEmpSalary(12.5f);

    employeeRepository.save(employee);

}

当我运行它时出现异常

java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotationAttributes(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/String;ZZ)Lorg/springframework/core/annotation/AnnotationAttributes;

at org.springframework.test.util.MetaAnnotationUtils$AnnotationDescriptor.<init>(MetaAnnotationUtils.java:290)
at org.springframework.test.util.MetaAnnotationUtils$UntypedAnnotationDescriptor.<init>(MetaAnnotationUtils.java:365)
at org.springframework.test.util.MetaAnnotationUtils$UntypedAnnotationDescriptor.<init>(MetaAnnotationUtils.java:360)
at org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes(MetaAnnotationUtils.java:191)
at org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes(MetaAnnotationUtils.java:198)
at 

进程结束,退出代码为 -1

最佳答案

看来您的问题已解决(混合 Spring 依赖版本),但让我扩展一下 @g00glen00b 关于如何编写单元测试的评论。

确保以下依赖项在您的 pom.xml 中:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

正如评论中指出的那样,@RunWith(SpringJUnit4ClassRunner.class) 导致单元测试启动整个应用程序,它用于集成测试。

幸运的是,Spring-boot 内置了对 Mockito 的依赖,这正是您进行此类单元测试所需要的。

现在,您的单元测试可能看起来像这样:

public class EmployeeRepositoryTest {

@InjectMocks
private EmployeeRepository employeeRepository;

@Mock
private Something something; // some class that is used inside EmployRepository (if any) and needs to be injected

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

@Test
public void insertEmploee(){

    Employee employee = new Employee();

    employee.setEmpName("Azad");
    employee.setEmpDesignation("Engg");
    employee.setEmpSalary(12.5f);

    employeeRepository.save(employee);

    Mockito.verify(...); // verify what needs to be verified
    }
}

可以找到关于使用 Mockito 的好帖子,例如 here .

关于java - Spring Boot 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452395/

相关文章:

java - Hibernate/JPA 单向 OneToMany 与源表中常量值的连接条件

java - 如何在Play框架应用程序中编写junit测试用例

java - 编写处理行尾断言的跨平台单元测试

java - 使用 Mockito 和 Junit 模拟 Jersey 客户端请求响应

java - 尚未定义 spring.config.import 属性 -> 将 spring-cloud-starter-config 添加到 pom.xml 后

java - 如何在Spring boot 2.0中实现CrudRepository的自定义方法?

java - 如何在运行时安排执行方法的特定时间

java - Web 应用程序中静态对象的范围是什么

java - 如何使用带有无效返回参数的 JPA 2.1 @NamedStoredProcedureQueries?

java - UI 相关对象可以保持可用多久?