質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
JUnit

JUnitは、Javaで開発されたプログラムのユニットテストを行うためのアプリケーションフレームワークです。簡単にプログラムのユニットテストを自動化することができ、結果もわかりやすく表示されるため効率的に開発時間を短縮できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Gradle

Gradleは、ビルド自動化ツールです。 ソフトウェアパッケージやドキュメント、 または実際に何か他の種類のプロジェクトの構築、テスト、公開、展開などを自動化が出来ます

Q&A

0回答

4588閲覧

JUnit5とJacocoレポートとJMockitの共存のさせ方を教えて下さい。

redanntube

総合スコア6

JUnit

JUnitは、Javaで開発されたプログラムのユニットテストを行うためのアプリケーションフレームワークです。簡単にプログラムのユニットテストを自動化することができ、結果もわかりやすく表示されるため効率的に開発時間を短縮できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Gradle

Gradleは、ビルド自動化ツールです。 ソフトウェアパッケージやドキュメント、 または実際に何か他の種類のプロジェクトの構築、テスト、公開、展開などを自動化が出来ます

0グッド

1クリップ

投稿2019/11/27 07:40

前提・実現したいこと

JUnit5とJacocoレポートとJMockitの共存のさせ方を教えて下さい。
JMockitを使ってクラスメソッドをMock化したテストコードを実行させたいのですが、
Gradle上だとエラーが発生してしまいます。
Eclipse上で動作させると上手く動作するのですが、Gradleコマンドを実行すると駄目です。
どなたかご教示頂けないでしょうか。

前提
SpringBoot2.1.6で開発しています。
JUnit4+PowerMockitを使ったレガシーコードが混在しており、カバレッジ反映の為に
Jacocoレポートの出力設定をbuild.gradleに記述しています。
将来的にはJUnit4とPowerMockitのレガシーコードを駆逐してJUnit5のテストコードに置き換えたいのですが、何処に不備があるのか分からず難儀しております。

発生している問題・エラーメッセージ

gradle

1jp.co.abc.efg.rest.controller.aa.TargetRestControllerTest > test002() FAILED 2 org.opentest4j.AssertionFailedError at TargetRestControllerTest.java:149 3 Caused by: java.lang.ArrayIndexOutOfBoundsException at TargetRestControllerTest.java:108

該当のソースコード

java

1// テストクラス 2import org.junit.jupiter.api.Assertions; 3import org.junit.jupiter.api.Test; 4import org.junit.jupiter.api.extension.ExtendWith; 5import org.springframework.beans.factory.annotation.Autowired; 6import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 7import org.springframework.boot.test.context.SpringBootTest; 8import org.springframework.test.annotation.Rollback; 9import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; 10import jp.co.abc.efg.MainApiApplication; 11import jp.co.abc.efg.core.bean.CommonUserInfo; 12import jp.co.abc.efg.core.common.CommonUtils; 13import jp.co.abc.efg.core.config.MyBatisConfiguration; 14import mockit.Mock; 15import mockit.MockUp; 16import mockit.integration.junit5.JMockitExtension; 17 18@SpringJUnitWebConfig(classes = {MainApiApplication.class , MyBatisConfiguration.class}) 19@SpringBootTest 20@AutoConfigureMockMvc 21@ExtendWith(JMockitExtension.class) 22public class TargetRestControllerTest { 23 @Autowired 24 private TargetRestController controller; 25 26 @Test 27 @Rollback(true) 28 public void test002() { 29 try { 30 new MockUp<CommonUtils>() { 31 @Mock 32 public CommonUserInfo getCommonUserInfo() { 33 var userInfo = new CommonUserInfo(); 34 userInfo.setUserid("12345678"); 35 userInfo.setKnjiempnm("てすと太郎"); 36 return userInfo; 37 } 38 }; 39 this.controller.refreshHierarchicalMenuInfo(); 40 } catch (Exception e) { 41 Assertions.fail(e); 42 } 43 } 44} 45 46// テスト対象クラス 47@RequestMapping(CommonApiEndPoints.BASE_URI) 48@RestController 49@CrossOrigin 50public class TargetRestController { 51 @Autowired 52 private TargetRestService service; 53 54 @GetMapping(value = CommonApiEndPoints.API_REFRESH_URI, produces = MediaType.APPLICATION_JSON_VALUE) 55 public ResponseJson<AsynchronousProcessingResponseResult> refreshHierarchicalMenuInfo() { 56 var responseJson = new ResponseJson<AsynchronousProcessingResponseResult>(); 57 String taskId = CommonUtils.createUUID(); 58 this.service.refreshHierarchicalMenuInfo(taskId, OlcScmCommonUtils.getCommonUserInfo()); 59 var asynchronousProcessingResponseResult = new AsynchronousProcessingResponseResult(); 60 asynchronousProcessingResponseResult.setPollingId(taskId); 61 CommonUtils.setResponseJson(responseJson, responseJson.createDateTime(), asynchronousProcessingResponseResult); 62 return responseJson; 63 } 64}

試したこと

build.gradleのtestタスクにてjvmArgsプロパティにJMockitとJacocoのjarを設定してみましたが、
Error occurred during initialization of VM
Error opening zip file or JAR manifest missing :
と出る始末。

補足情報(FW/ツールのバージョンなど)

gradle

1------------------------------------------------------------ 2Gradle 5.6.4 3------------------------------------------------------------ 4 5Build time: 2019-11-01 20:42:00 UTC 6Revision: dd870424f9bd8e195d614dc14bb140f43c22da98 7 8Kotlin: 1.3.41 9Groovy: 2.5.4 10Ant: Apache Ant(TM) version 1.9.14 compiled on March 12 2019 11JVM: 11.0.5 (Oracle Corporation 11.0.5+10-LTS) 12OS: Windows 10 10.0 amd64 13 14// build.gradleは以下の通りです 15buildscript { 16 ext { 17 springBootVersion = '2.1.6.RELEASE' 18 springframeworkVersion = '5.1.9.RELEASE' 19 junit5Version = '5.5.1' 20 jacocoVersion = '0.8.5' 21 } 22 repositories { 23 mavenCentral() 24 } 25 dependencies { 26 classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 27 } 28} 29 30apply plugin: 'java' 31apply plugin: 'eclipse' 32apply plugin: 'org.springframework.boot' 33apply plugin: 'io.spring.dependency-management' 34apply plugin: 'jacoco' 35 36sourceCompatibility = 11 37targetCompatibility = 11 38 39repositories { 40 mavenCentral() 41} 42 43tasks.withType(JavaCompile) { 44 options.encoding = 'UTF-8' 45 options.compilerArgs = ["-Xlint:deprecation", "-Xlint:unchecked"] 46} 47 48jacoco { 49 toolVersion = "${jacocoVersion}" 50} 51 52configurations { 53 jacoco 54 jacocoRuntime 55} 56 57dependencies { 58 compile("org.springframework.boot:spring-boot-starter-jdbc:${springBootVersion}") 59 compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") 60 compile("org.springframework.boot:spring-boot-starter-cache:${springBootVersion}") 61 compile("org.springframework.boot:spring-boot-starter-aop:${springBootVersion}") 62 compile("org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}") 63 compile("org.springframework.boot:spring-boot-starter-mail:${springBootVersion}") 64 compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:latest.integration') 65 compile('org.apache.tomcat:tomcat-jdbc:latest.integration') 66 compile('org.apache.commons:commons-lang3:latest.integration') 67 compile('commons-codec:commons-codec:latest.integration') 68 compile('commons-io:commons-io:latest.integration') 69 compile('org.hibernate.validator:hibernate-validator:latest.integration') 70 compile('org.projectlombok:lombok:latest.integration') 71 annotationProcessor('org.projectlombok:lombok:latest.integration') 72 compile('javax.cache:cache-api:latest.integration') 73 compile('org.ehcache:ehcache:latest.integration') 74 compile('io.github.classgraph:classgraph:latest.integration') 75 implementation('com.google.code.findbugs:jsr305:latest.integration') 76 compile files('lib/ojdbc8.jar') 77 compile files('lib/orai18n.jar') 78 compile files('lib/orai18n-mapping.jar') 79 compile files('lib/ucp.jar') 80 testCompile('org.springframework.boot:spring-boot-starter-test') { 81 //exclude module: 'junit' // JUnit4 exclude. 82 exclude group: "org.mockito", module: "mockito-core" 83 } 84 testImplementation("org.junit.jupiter:junit-jupiter-api:${junit5Version}") { 85 exclude group: "org.junit.platform", module: "junit-platform-commons" 86 } 87 testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junit5Version}") 88 testRuntimeOnly("org.junit.jupiter:junit-jupiter-params:${junit5Version}") 89 testRuntimeOnly('org.junit.platform:junit-platform-launcher:latest.integration') 90 testRuntimeOnly('org.junit.platform:junit-platform-commons:latest.integration') 91 testRuntimeOnly('org.junit.platform:junit-platform-engine:latest.integration') 92 testCompile('org.mockito:mockito-core:latest.integration') 93 testCompile('org.mockito:mockito-junit-jupiter:latest.integration') { 94 exclude group: "org.junit.platform", module: "junit-platform-commons" 95 } 96 testCompile('org.powermock:powermock-api-mockito2:latest.integration') 97 testCompile('org.powermock:powermock-module-junit4:latest.integration') 98 testAnnotationProcessor('org.projectlombok:lombok:latest.integration') 99 testCompile("org.springframework.boot:spring-boot-starter-mail:${springBootVersion}") 100 testCompile('org.jmockit:jmockit:latest.integration') 101 testRuntimeOnly("org.jacoco:org.jacoco.ant:${jacocoVersion}:nodeps") 102 testRuntimeOnly("org.jacoco:org.jacoco.agent:${jacocoVersion}:runtime") 103 testRuntimeOnly('org.junit.vintage:junit-vintage-engine:latest.integration') 104} 105 106test { 107 dependsOn = ['instrument'] 108 useJUnitPlatform() 109 jvmArgs "-javaagent:${classpath.find { it.name.contains("jmockit") }.absolutePath}" 110 finalizedBy = ['jacocoTestReport'] 111} 112 113task instrument(dependsOn: [classes, project.configurations.jacocoAnt]) { 114 inputs.files classes.outputs.files 115 File outputDir = new File(project.buildDir, 'instrumentedClasses') 116 outputs.dir outputDir 117 ext.instrumentedOutputDir = project.buildDir.path + '/instrumentedClasses' 118 doFirst { 119 project.delete(outputDir) 120 ant.taskdef( 121 resource: 'org/jacoco/ant/antlib.xml', 122 classpath: project.configurations.jacocoAnt.asPath, 123 uri: 'jacoco' 124 ) 125 def instrumented = false 126 if (file(sourceSets.main.java.outputDir).exists()) { 127 def instrumentedClassedDir = "${outputDir}/${sourceSets.main.java}" 128 ant.'jacoco:instrument'(destdir: instrumentedClassedDir) { 129 fileset(dir: sourceSets.main.java.outputDir, includes: '**/*.class') 130 } 131 sourceSets.test.runtimeClasspath -= files(sourceSets.main.java.outputDir) 132 sourceSets.test.runtimeClasspath += files(instrumentedClassedDir) 133 instrumented = true 134 } 135 if (instrumented) { 136 test.jvmArgs += '-noverify' 137 } 138 } 139} 140 141gradle.taskGraph.whenReady { graph -> 142 if ( graph.hasTask(instrument) ) { 143 tasks.withType( Test ) { 144 doFirst { 145 systemProperty 'jacoco-agent.destfile', project.buildDir.path + '/jacoco/test.exec' 146 classpath = classpath + files(instrument.instrumentedOutputDir) + project.configurations.jacocoRuntime 147 } 148 } 149 } 150} 151 152jacocoTestReport { 153 dependsOn = ['instrument', 'test'] 154 additionalSourceDirs = files(sourceSets.main.allJava.srcDirs) 155 reports { 156 xml.enabled true 157 csv.enabled false 158 html.enabled true 159 sourceSets sourceSets.main 160 } 161 afterEvaluate { 162 classDirectories = files( classDirectories.files.collect { 163 fileTree(dir: it, 164 exclude: [ 165 'jp/co/abc/efg/core/bean/**', 166 'jp/co/abc/efg/rest/dto/**', 167 'jp/co/abc/efg/rest/mybatis/dto/**' 168 169 ] 170 ) 171 }) 172 } 173}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問