Spring Boot 单元测试

Sai*_*zad 5 java junit 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);

}
Run Code Online (Sandbox Code Playgroud)

}

当我运行它时,我得到异常

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 
Run Code Online (Sandbox Code Playgroud)

进程完成,退出代码 -1

Sma*_*ajl 2

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

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

正如评论中指出的,@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
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,可以在这里找到有关使用 Mockito 的好文章。