我是 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/