测试在Maven中成功运行,而在Gradle中失败
我的Spring Boot应用程序(版本2.1.0)有一个奇怪的问题,该应用程序使用JPA(spring-boot-starter-data-jpa)与mysql db进行集成,我定义了一些集成测试用例,它们使用TestRest模板,但这已通过maven(3.5.4)测试命令成功运行,而在Gradle(4.6)失败,我们试图为pom.xml和build.gradle设置相同的配置
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.eudsys.spring.integ</groupId>
<artifactId>integration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>integration</name>
<description>Eudsys project for Spring Integration</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>auth0-spring-security-api</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.4.0.905</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.1</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.5</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
build.gradle
buildscript {
ext {
springBootVersion = '2.1.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.5"
}
}
plugins {
id 'java'
id 'war'
id 'org.gretty' version '2.2.0'
}
plugins {
id "org.sonarqube" version "2.5"
}
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'org.gretty'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'org.sonarqube'
apply plugin: 'jacoco'
bootJar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}
repositories {
mavenCentral()
jcenter()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
runtime 'javax.servlet:jstl:1.1.2'
compile group: 'com.sun.mail', name: 'javax.mail', version:'1.5.5'
compile group: 'org.projectlombok', name: 'lombok', version:'1.18.2'
compile group: 'net.bytebuddy', name: 'byte-buddy', version: '1.8.0'
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.5'
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
compile('com.fasterxml.jackson.core:jackson-core')
compile('javax.xml.bind:jaxb-api:2.3.0')
compile("com.auth0:java-jwt:3.4.0")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.boot:spring-boot-starter-actuator")
runtime(group: 'mysql', name: 'mysql-connector-java', version:'8.0.13') {
exclude(module: 'protobuf-java')
}
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile 'junit:junit:4.12'
}
jacoco {
toolVersion = "0.8.1"
reportsDir = file("$buildDir/customJacocoReportDir")
}
test {
jacoco {
append = false
destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
classDumpDir = file("$buildDir/jacoco/classpathdumps")
}
testLogging {
showStandardStreams = true
}
}
jacocoTestReport {
reports {
xml.enabled false
csv.enabled false
html.destination file("${buildDir}/jacocoHtml")
}
}
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.2
}
}
rule {
enabled = false
element = 'CLASS'
includes = ['org.gradle.*']
limit {
counter = 'LINE'
value = 'TOTALCOUNT'
maximum = 0.3
}
}
}
}
gradle中的TestController失败,但在maven中工作正常
package com.eudsys.spring;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.eudsys.spring.db.Account;
import com.eudsys.spring.db.ApplicationUser;
import com.eudsys.spring.db.Branch;
import com.eudsys.spring.db.Company;
import com.eudsys.spring.db.SecurityQuestion;
import com.eudsys.spring.db.UserBranch;
import com.eudsys.spring.db.UserQuestion;
import com.eudsys.spring.db.UsersDetail;
import com.eudsys.spring.util.RandomString;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@EnableSpringDataWebSupport
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UserManagementUpdateTest {
private static RandomString randomString = new RandomString(10);
private static String RANDOM_EMAIL = randomString.nextString() + "@yopmail.com";
private static String RANDOM_INVITE_EMAIL = randomString.nextString() + "@yopmail.com";
private static String RANDOM_COMP_NAME = "Partho_" + randomString.nextString();
private static String RANDOM_COMP_LICENC = randomString.nextString();
private static Long RANDOM_COMP_DUNS_NUM = (randomString.generateNumber() / 1000);
private static Long RANDOM_PHONE = randomString.generateNumber();
private static Long RANDOM_INVITE_PHONE = randomString.generateNumber();
private static String CORP_TYPE = "CORP";
private static String REGISTER_REQUEST = null;
private static String UPDATE_CORP_REQUEST = null;
private static String FORGET_LOGIN_REQUEST = null;
private static String FORGET_EMAIL_REQUEST = null;
private static String RESET_PASSWD_REQUEST = null;
private static String LOGIN_REQUEST = null;
private static String NEW_BRANCH_REQUEST = null;
private static String INVITE_REQUEST = null;
private static String COMPANY_EDIT_REQUEST = null;
private static String EMAIL_TOKEN = "EMAILTOKEN";
private static String EMAIL_INVITE_TOKEN = "EMAILTOKEN";
private static String AUTH_TOKEN = "AUTHTOKEN";
private static String TESTLOGIN = "test" + randomString.nextString();
private static String TESTINVITELOGIN = "test" + randomString.nextString();
private static String TESTANSWER = "testanswer";
private static int TESTQUESTION = 1;
private static int TESTACCOUNT = 1;
private static ApplicationUser userfound = new ApplicationUser();
private static Account accountFound = new Account();
private static ApplicationUser inviteUserfound = new ApplicationUser();
private static Account inviteAccountFound = new Account();
private static UserQuestion question = new UserQuestion();
private static Branch branchCreated=new Branch();
private static SecurityQuestion securityquestion = new SecurityQuestion();
MockMvc mockMvc;
@Autowired
IntegrationApplication integrationApplication;
@Autowired
private TestRestTemplate template;
@Mock
private static UserManagementController userManagementController;
@InjectMocks
@Autowired
private UserManagementUpdateController userManagementUpdateController;
@Before
public void setup() throws Exception {
try {
mockMvc = MockMvcBuilders.standaloneSetup(userManagementController, userManagementUpdateController).build();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void test1AllUsers() throws Exception {
ResponseEntity<List> response = template.getForEntity("/employees", List.class);
System.out.println(response.getStatusCode().value());
Assert.assertEquals(200, response.getStatusCode().value());
response = template.getForEntity("/employees", List.class);
System.out.println(response.getStatusCode().value());
Assert.assertEquals(200, response.getStatusCode().value());
}
@Test
public void test2BRegisterUser() throws Exception {
REGISTER_REQUEST = "{\"loginid\":\"" + TESTLOGIN + "\",\"email\":\"" + RANDOM_EMAIL + "\"," + "\"type\":\""
+ CORP_TYPE + "\"}";
HttpEntity<Object> applicationUser = postHttpEntity(REGISTER_REQUEST);
ResponseEntity<ApplicationUser> response = template.postForEntity("/register", applicationUser,
ApplicationUser.class);
Assert.assertEquals(200, response.getStatusCode().value());
if (response.getBody() != null) {
userfound = response.getBody();
EMAIL_TOKEN = userfound.getEmail_token();
TESTACCOUNT = userfound.getAccount().getId();
System.out.println(" User Found : " + userfound);
// userRepository.
}
}
@Test
public void test4DCanLogin() throws Exception {
LOGIN_REQUEST = "{\"login\":\"" + TESTLOGIN + "\",\"password\":\"" + RANDOM_COMP_NAME + "\"}";
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, AUTH_TOKEN);
HttpEntity<List> requestEntity = new HttpEntity<>(null, headers);
HttpEntity<Object> applicationUser = postHttpEntity(LOGIN_REQUEST);
ResponseEntity<String> response = template.postForEntity("/login", applicationUser, String.class);
Assert.assertEquals(200, response.getStatusCode().value());
List<String> token = response.getHeaders().get(HttpHeaders.AUTHORIZATION);
System.out.println("\n\n\n Token" + token);
AUTH_TOKEN = token.get(0);
}
@Test
public void test8ResetPassword() throws Exception {
RESET_PASSWD_REQUEST= "{\"login\":\""+TESTINVITELOGIN+"\",\"password\":\""+TESTANSWER+"\"}";
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, AUTH_TOKEN);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> requestEntity = new HttpEntity<Object>(RESET_PASSWD_REQUEST, headers);
// verify the forget password service with login id
ResponseEntity<ApplicationUser> response = template.exchange("/resetpassword", HttpMethod.POST, requestEntity,
ApplicationUser.class);
assertEquals(200, response.getStatusCode().value());
}
@Test
public void testFindBranchWithId() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, AUTH_TOKEN);
HttpEntity<ApplicationUser> requestEntity = new HttpEntity<>(null, headers);
ResponseEntity<List> response = template.exchange("/branches/" + TESTLOGIN, HttpMethod.GET, requestEntity,
List.class);
System.out.println("\n\n" + response);
Assert.assertEquals(200, response.getStatusCode().value());
}
@Test
public void testCanRegisterDetails() throws Exception {
ResponseEntity<ApplicationUser> response = template.getForEntity("/registerdetails/" + EMAIL_TOKEN,
ApplicationUser.class);
System.out.println(response);
Assert.assertEquals(200, response.getStatusCode().value());
response = template.getForEntity("/registerdetails/dOevI9", ApplicationUser.class);
System.out.println(response);
Assert.assertNotEquals(200, response.getStatusCode().value());
}
@Test
public void testListOfQuestions() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, AUTH_TOKEN);
HttpEntity<ApplicationUser> requestEntity = new HttpEntity<>(null, headers);
ResponseEntity<List> response = template.exchange("/questions", HttpMethod.GET, requestEntity, List.class);
System.out.println(response);
Assert.assertEquals(200, response.getStatusCode().value());
}
@Test
public void test9UserNRoles() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, AUTH_TOKEN);
HttpEntity<List> requestEntity = new HttpEntity<>(null, headers);
ResponseEntity<ApplicationUser> response = template.exchange("/users/1", HttpMethod.GET, requestEntity,
ApplicationUser.class);
System.out.println(response);
Assert.assertEquals(200, response.getStatusCode().value());
response = template.exchange("/users/"+TESTLOGIN, HttpMethod.GET, requestEntity, ApplicationUser.class);
System.out.println(response);
Assert.assertEquals(200, response.getStatusCode().value());
}
private HttpEntity<Object> postHttpEntity(Object body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<Object>(body, headers);
}
@AfterClass
public static void cleanUp() throws Exception {
if (userfound != null) {
try {
Account account = userfound.getAccount();
UsersDetail userDetail = userfound.getUsersDetail();
Company company =account.getCompany();
UserQuestion question =userfound.getUserQuestion();
Collection<Branch> branchs = null;
if (company != null) {
branchs = branchRepository.findByCompanyId(company.getId());
}
System.out.println(" User before delete :" + userfound);
userRepository.delete(userfound);
userRepository.flush();
System.out.println(" User after delete :" + userfound);
/*
* accountRepository.delete(account);accountRepository.flush();
* companyRepository.delete(company);companyRepository.flush();
* userDetailsRepository.delete(userDetail);userDetailsRepository.flush();
* userQuestionRepository.delete(question);userQuestionRepository.flush();
* if(branchs!=null) for (Branch branch : branchs) {
* branchRepository.delete(branch); List<UserBranch> userBranchs =
* branch.getUserBranchList(); for (UserBranch userBranch : userBranchs) {
* userBranchRepository.delete(userBranch); } }
*/
} catch (Exception e) {
System.out.println("\n\n\n E :" + e.getMessage());
e.printStackTrace();
}
}
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
@Mock
private static UserRepository userRepository;
@Mock
private static UserDetailsRepository userDetailsRepository;
@Mock
private static AccountRepository accountRepository;
@Mock
private static CompanyRepository companyRepository;
@Mock
private static UserQuestionRepository userQuestionRepository;
@Mock
private static SecurityQuestionRepository securityQuestionRepository;
@Mock
private static RoleRepository roleRepository;
@Mock
private static BranchRepository branchRepository;
@Mock
private static UserBranchRepository userBranchRepository;
}
error stack
2019-01-02 19:41:50.350 DEBUG 1156 --- [ Test worker] c.e.spring.UserManagementUpdateTest : Running with Spring Boot v2.0.5.RELEASE, Spring v5.0.9.RELEASE
2019-01-02 19:41:50.351 INFO 1156 --- [ Test worker] c.e.spring.UserManagementUpdateTest : No active profile set, falling back to default profiles: default
2019-01-02 19:41:51.247 WARN 1156 --- [ Test worker] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
2019-01-02 19:41:51.256 ERROR 1156 --- [ Test worker] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
答案 0 :(得分:0)
好像您缺少依赖项。试试这个依赖块。根据您的项目更新jar版本。
dependencies {
compile "org.springframework.boot:spring-boot-starter-data-jpa:*"
compile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final"
compile "org.springframework.boot:spring-boot-starter-web:*"
compile "org.springframework.boot:spring-boot-starter-security:*"
compile "org.springframework.boot:spring-boot-starter:*"
compile "mysql:mysql-connector-java:*"
compile "com.sun.mail:javax.mail:1.5.5"
compile "org.projectlombok:lombok:*"
testCompile "org.springframework.boot:spring-boot-starter-test:*"
testCompile "junit:junit:4.12"
compile "org.springframework.security:spring-security-crypto:5.0.5.RELEASE"
compile "com.auth0:auth0-spring-security-api:1.1.0"
compile "com.google.code.gson:gson:2.8.5"
compile "com.fasterxml.jackson.core:jackson-databind:2.9.5"
testCompile "org.mockito:mockito-all:1.9.5"
}