java – Spring Boot Unit Test

我是春季靴子的新手.需要一些建议

这是我的单元测试课

@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.

点赞