Lar*_*sse 13 java unit-testing spring-test mockito gradle
所以我在 Spring boot Gradle 项目中收到此错误:
'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'
java.lang.NoSuchMethodError: 'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'
Run Code Online (Sandbox Code Playgroud)
我似乎无法修复它。我已经搜索了答案,但我得到的唯一答案是从依赖项中删除mockito-all,但我一开始就没有在我的 gradle.build 文件中添加它。
我的 build.gradle 文件:
plugins {
id 'org.springframework.boot' version '2.4.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id "org.sonarqube" version "3.0"
id 'jacoco'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
implementation('io.jsonwebtoken:jjwt:0.2')
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compile 'junit:junit:4.12'
implementation 'org.modelmapper:modelmapper:2.4.1'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.eclipse.jgit:org.eclipse.jgit:5.4.2.201908231537-r'
/**
* JUnit jupiter with mockito.
*/
testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.19.0'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
testCompile group: 'org.springframework.security', name: 'spring-security-test', version: '5.1.6.RELEASE'
}
sonarqube{
properties{
property 'sonarjava.source', '1.8'
property 'sonar.java.coveragePlugin', 'jacoco'
property 'sonar.jacoco.reportPaths', 'build/reports/jacoco/test/jacocoTestReport.xml'
}
}
test {
useJUnitPlatform()
}
Run Code Online (Sandbox Code Playgroud)
我似乎找不到解决方案,所以我来到这里,一些代码大神也许可以帮助我解决我的问题。
我收到此错误的文件是一个测试类:
测试类:
package com.example.demo.Service;
import com.example.demo.DTO.PartyLeaderDto;
import com.example.demo.Model.PartyLeader;
import com.example.demo.Repository.PartyLeaderRepository;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.verify;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.modelmapper.ModelMapper;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.argThat;
@SpringBootTest
@AutoConfigureMockMvc
public class PartyLeaderServiceMockTest {
@Rule
public MockitoRule initRule = MockitoJUnit.rule();
@Mock
private PartyLeaderRepository partyLeaderRepository;
@Mock
private ModelMapper modelMapper;
@InjectMocks
private PartyLeaderService partyLeaderService; // this is like calling new PartyLeaderService(partyLeaderRepository, modelMapper);
@Test
void whenSavePartyLeader_thenCorrectPartyLeaderSaved() {
// given
var input = PartyLeaderDto.builder()
.name("Josse")
.apperance("Link of image")
.build();
// when
partyLeaderService.savePartyLeader(input);
// then
verify(partyLeaderRepository).save(argThat(entity ->
entity.getName().equals("Josse")
&& entity.getApperance().equals("Link of image")));
}
@Test
void whenGetPartyLeader_ShouldReturnCorrectLeaderData() {
// given
var partyLeaderEntity = PartyLeader.builder()
.name("Josse")
.apperance("Link of image")
.build();
var partyLeaderDto = PartyLeaderDto.builder()
.name("Josse")
.apperance("Link of image")
.build();
when(partyLeaderRepository.findById(3)).thenReturn(Optional.of(partyLeaderEntity));
when(modelMapper.map(partyLeaderEntity, PartyLeaderDto.class)).thenReturn(partyLeaderDto);
// when
var result = partyLeaderService.getPartyLeader(3);
// then
Assert.assertEquals(result, partyLeaderDto);
}
}
Run Code Online (Sandbox Code Playgroud)
我在两次测试中都遇到相同的错误。
谁能帮我?提前致谢!
小智 14
问题是由于 jar 冲突造成的
我们需要排除
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
</exclusion>
</exclusions>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并包括
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
面对同样的问题后。请查看日志跟踪。
\njava.lang.NoSuchMethodError: org.mockito.MockitoAnnotations.openMocks(Ljava/lang/Object;)Ljava/lang/AutoCloseable;\n at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.initMocks(MockitoTestExecutionListener.java:83)\nRun Code Online (Sandbox Code Playgroud)\n终于得到了解决方案:
\n在Mockito 版本 2中,有一个MockitoAnnotations.initMock()方法,该方法已被弃用,并在Mockito JUnit 5 版本 3中替换为 MockitoAnnotations.openMocks() 。MockitoAnnotations.openMocks ()方法返回 AutoClosable 的实例,可用于在测试后关闭资源。
\n手动初始化
\n在做任何其他事情之前,我们必须添加 Mockito 依赖项。
\ndependencies {\n testImplementation('org.mockito:mockito-core:3.7.7')\n}\nRun Code Online (Sandbox Code Playgroud)\nMockitoAnnotations.openMocks(this) 调用告诉 Mockito 扫描此测试类实例以查找使用 @Mock 注释注释的任何字段,并将这些字段初始化为模拟。
\n优点:
\n易于创建模拟\n非常可读
\n缺点:
\n不验证框架使用情况或检测不正确的存根\n自动模拟注入\n我们还可以告诉 Mockito 自动将模拟注入到使用 @InjectMocks 注释的字段中。
\n当MockitoAnnotations.openMocks()被调用时,Mockito 将:
\n为使用 @Mock 注释进行注释的字段创建模拟\n创建使用 @InjectMocks 注释的字段的实例,并尝试将模拟注入其中\n使用 @InjectMocks 与我们手动实例化实例时的操作相同,但现在是自动的。
\npublic class MockitoInjectMocksTests {\n\n @Mock\n private OrderRepository orderRepository;\n private AutoCloseable closeable;\n @InjectMocks\n private OrderService orderService;\n\n @BeforeEach\n void initService() {\n closeable = MockitoAnnotations.openMocks(this);\n }\n\n @AfterEach\n void closeService() throws Exception {\n closeable.close();\n }\n\n @Test\n void createOrderSetsTheCreationDate() {\n Order order = new Order();\n when(orderRepository.save(any(Order.class))).then(returnsFirstArg());\n\n Order savedOrder = orderService.create(order);\n\n assertNotNull(savedOrder.getCreationDate());\n }\n}\nRun Code Online (Sandbox Code Playgroud)\nMockito 将首先尝试通过构造函数注入来注入模拟,然后是 setter 注入或字段注入。
\n优点:
\n易于注入模拟
\n缺点:
\n\xe2\x80\x99t 不强制使用构造函数注入
\n| 归档时间: |
|
| 查看次数: |
36711 次 |
| 最近记录: |