Why my Spock unit tests fail in Gradle build after upgrading to JDK 8? - unit-testing

I'm trying to compile my application source using JDK 8, Groovy 2.4.4, Spock 1.0-groovy-2.4, Gradle 1.11 (my firm hass custom plugins built on top of this)
gradle -version
Groovy: 1.8.6
Ant: Apache Ant(TM) version 1.9.2 compiled on July 8 2013
Ivy: 2.2.0
JVM: 1.7.0_51 (Oracle Corporation 24.51-b03)
OS: Windows 7 6.1 amd64
In my build environment, I need to retain my JAVA_HOME to Java 7 for other projects.
JAVA_HOME = C:\Program Files\Java\jdk1.7.0_51
JAVA8_HOME = C:\Program Files\Java\jdk1.8.0_60
Due to this, in my build.gradle, I explicitly tell Gradle to use JDK 8
tasks.withType(JavaCompile) {
options.fork = true;
options.forkOptions.executable = "${System.env.JAVA8_HOME}/bin/javac"
}
tasks.withType(Test) {
executable = "${System.env.JAVA8_HOME}/bin/java"
}
compileJava{
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
The source files compile successfully, however when it reached unit tests (written in Spock), it fails with the below error.
Caused by: java.lang.UnsupportedClassVersionError: org/model/SDA : Unsupported major.minor version 52.0
I confirmed that SDA.class is compiled using JDK 8.
javap -verbose SDA.class | findstr "major"
major version: 52
Any reason why only during unit tests I get the above error? Does that mean unit test is being run on JDK 7?

So if you're really into hacks there is something you can do. It does involve overriding some of the Gradle internals - so it may not work on any version of Gradle other than 1.11. There may also be unexpected side-effects.
import org.gradle.internal.Factory
import org.gradle.process.internal.WorkerProcessBuilder
import org.gradle.api.internal.tasks.compile.daemon.CompilerDaemonStarter
tasks.withType(GroovyCompile) {
options.fork = true
options.forkOptions.executable = "${System.env.JAVA8_HOME}/bin/javac"
doFirst {
def compilerFactory = compiler.compiler.compilerFactory
def clientsManager = compilerFactory.compilerDaemonManager.clientsManager
def oldDaemonStarter = clientsManager.compilerDaemonStarter
if (!(oldDaemonStarter.workerFactory instanceof CustomWorkerProcessFactory)) {
println "HACK, installing custom daemon worker"
clientsManager.compilerDaemonStarter = new CompilerDaemonStarter(
new CustomWorkerProcessFactory(oldDaemonStarter.workerFactory),
oldDaemonStarter.startParameter)
}
}
}
class CustomWorkerProcessFactory implements Factory<WorkerProcessBuilder> {
Factory<WorkerProcessBuilder> delegate
CustomWorkerProcessFactory(Factory<WorkerProcessBuilder> delegate) {
this.delegate = delegate
}
public WorkerProcessBuilder create() {
def newWorker = delegate.create()
newWorker.javaCommand.executable("${System.env.JAVA8_HOME}/bin/java")
newWorker
}
}

Add this to your gradle.properties:
org.gradle.java.home=/path/to/java8
Or when you launch gradle, you can specify it as a jvm parameter:
gradle -Dorg.gradle.java.home=/path/to/java8 task1 task2

Related

HttpClient Get or Post doesn't work with .NETCore 2.1 and 2.2, but works with .NETCore 2.0

I use Visual Studio 2017 v15.9.4, .NET Standard 2.0.3 and the last version of .NETCore 2.1.6. I run my application on Windows 10 64bits.
This code :
using (HttpClient client = new HttpClient())
{
try
{
var response = await client.GetAsync("http://httpbin.org/")
...
doesn't work with the last version of .NET Core 2.1 or 2.2.
I have this exception :
Result StackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at EliorNugetCommon.Tests.APIManagerTests.Get() in D:\Git\Elior-Group\WebApiServices\NugetWAS\EliorNugetCommon\EliorNugetCommon.Tests\APIManagerTests.cs:line 50
----- Inner Stack Trace -----
Result Message:
System.AggregateException : One or more errors occurred. (A task was canceled.)
---- System.Threading.Tasks.TaskCanceledException : A task was canceled.
But, that works with .NET Core 2.0.9 !
Thank you for your help.
With the new HTTP stack in .NET Core and .NET Core 2.2, there is a regression with the authentification behind a proxy. In this case, we can use the .NET Core 2.0 HTTP stack this switch :
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
For more information, the discussion is here : https://github.com/dotnet/corefx/issues/30166

Testing ASP.NET Core full .NET Framework with TestServer gives method not found in vs 2017

When trying to run test in Visual Studio 2017, all is compiling without issue,
However when I'm trying to create server and client to test:
this.Server = new TestServer(
new WebHostBuilder()
.UseStartup<Startup>()
.UseContentRoot(di.FullName));
this.Client = this.Server.CreateClient();
The TestServeris complaining about wrong dependencies (it tries to load version 1.0.0) even if TestHost package is:
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="1.1.1" />
Also test is failing with exception:
Cannot find method: 'System.Net.Http.HttpClient Microsoft.AspNetCore.TestHost.TestServer.CreateClient()'..
It is related to wrong test template in VS 2017
manually adding in the top <PropertyGroup>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
in csproj file fixes issue

Other referenced package cannot be found in test

In my project (if you want detailed information, you can find it on Github) I've got two modules:
app (the default module generated when you start out with a new Android project)
dice (new module, which is a dice rolling domain model package)
I've started out fleshing out my MVP classes in the app module, and I want to reuse the PredefinedRandomIntegerGenerator class (on Github) from the dice module (residing the test folder of that module) in my unit tests in the app module.
When I started writing my test code I encountered no problems, until I started running my
C:\Projects\Dice-Statistics\app\src\test\java\com\xilconic\dicestatistics\viewmodels\SixSidedDieRollingViewModelTest.java:5: error: package com.xilconic.gaming.dice.test.mocks does not exist
import com.xilconic.gaming.dice.test.mocks.PredefinedRandomIntegerGenerator;
^
C:\Projects\Dice-Statistics\app\src\test\java\com\xilconic\dicestatistics\viewmodels\SixSidedDieRollingViewModelTest.java:21: error: cannot find symbol
RandomIntegerGenerator rng = new PredefinedRandomIntegerGenerator(results);
^
symbol: class PredefinedRandomIntegerGenerator
location: class SixSidedDieRollingViewModelTest
I have no clue why during the build the com.xilconic.gaming.dice.test.mocks package can't be found. Am I missing something in my Gradle script for the app module? That looks as follows:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.xilconic.dicestatistics"
minSdkVersion 8
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile project(':dice')
}
Any help would be very welcome!

Managed .NET application starter [duplicate]

A similar question was asked here, but it was specific to .NET 3.5. Specifically, I'm looking for the following:
What is the correct way to determine which .NET Framework versions and service packs are installed?
Is there a list of registry keys that can be used?
Are there any dependencies between Framework versions?
The registry is the official way to detect if a specific version of the Framework is installed.
Which registry keys are needed change depending on the Framework version you are looking for:
Framework Version Registry Key
------------------------------------------------------------------------------------------
1.0 HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705
1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install
2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install
3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess
3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install
4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install
Generally you are looking for:
"Install"=dword:00000001
except for .NET 1.0, where the value is a string (REG_SZ) rather than a number (REG_DWORD).
Determining the service pack level follows a similar pattern:
Framework Version Registry Key
------------------------------------------------------------------------------------------
1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version
1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version
1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP
2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP
3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP
3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing
4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing
[1] Windows Media Center or Windows XP Tablet Edition
As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.
For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.
While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:
Framework Version Registry Key
------------------------------------------------------------------------------------------
1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version
1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version
1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322
2.0[2] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version
2.0[3] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment
3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version
3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version
4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version
[1] Windows Media Center or Windows XP Tablet Edition
[2] .NET 2.0 SP1
[3] .NET 2.0 Original Release (RTM)
Again, .NET 1.0 uses a string value while all of the others use a DWORD.
Additional Notes
for .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The #,#,#### portion of the string is the Framework version.
for .NET 1.1, we use the name of the registry key itself, which represents the version number.
Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.
.NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.
Update for .NET 4.5
There won't be a v4.5 key in the registry if .NET 4.5 is installed. Instead you have to check if the HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full key contains a value called Release. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found here and here.
There is an official Microsoft answer to this question at the following knowledge base article:
Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1
How to determine which versions of the .NET Framework are installed and whether service packs have been applied
Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... why would the official Microsoft answer be so misinformed?
The Framework 4 beta installs to a differing registry key.
using System;
using System.Collections.ObjectModel;
using Microsoft.Win32;
class Program
{
static void Main(string[] args)
{
foreach(Version ver in InstalledDotNetVersions())
Console.WriteLine(ver);
Console.ReadKey();
}
public static Collection<Version> InstalledDotNetVersions()
{
Collection<Version> versions = new Collection<Version>();
RegistryKey NDPKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP");
if (NDPKey != null)
{
string[] subkeys = NDPKey.GetSubKeyNames();
foreach (string subkey in subkeys)
{
GetDotNetVersion(NDPKey.OpenSubKey(subkey), subkey, versions);
GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey("Client"), subkey, versions);
GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey("Full"), subkey, versions);
}
}
return versions;
}
private static void GetDotNetVersion(RegistryKey parentKey, string subVersionName, Collection<Version> versions)
{
if (parentKey != null)
{
string installed = Convert.ToString(parentKey.GetValue("Install"));
if (installed == "1")
{
string version = Convert.ToString(parentKey.GetValue("Version"));
if (string.IsNullOrEmpty(version))
{
if (subVersionName.StartsWith("v"))
version = subVersionName.Substring(1);
else
version = subVersionName;
}
Version ver = new Version(version);
if (!versions.Contains(ver))
versions.Add(ver);
}
}
}
}
I wanted to detect for the presence of .NET version 4.5.2 installed on my system, and I found no better solution than ASoft .NET Version Detector.
Snapshot of this tool showing different .NET versions:
Enumerate the subkeys of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP. Each subkey is a .NET version. It should have Install=1 value if it's present on the machine, an SP value that shows the service pack and an MSI=1 value if it was installed using an MSI. (.NET 2.0 on Windows Vista doesn't have the last one for example, as it is part of the OS.)
For a 64-bit OS, the path would be:
HKEY_LOCAL_MACHINE\SOFTWARE\wow6432Node\Microsoft\NET Framework Setup\NDP\
Update for .NET 4.5.1
Now that .NET 4.5.1 is available the actual value of the key named Release in the registry needs to be checked, not just its existence. A value of 378758 means that .NET Framework 4.5.1 is installed. However, as described here this value is 378675 on Windows 8.1.
There is a GUI tool available, ASoft .NET Version Detector, which has always proven highly reliable. It can create XML files by specifying the file name of the XML output on the command line.
You could use this for automation. It is a tiny program, written in a non-.NET dependent language and does not require installation.
I was needing to find out just which version of .NET framework I had on my computer, and all I did was go to the control panel and select the "Uninstall a Program" option. After that, I sorted the programs by name, and found Microsoft .NET Framework 4 Client Profile.
Here is a PowerShell script to obtain installed .NET framework versions
function Get-KeyPropertyValue($key, $property)
{
if($key.Property -contains $property)
{
Get-ItemProperty $key.PSPath -name $property | select -expand $property
}
}
function Get-VersionName($key)
{
$name = Get-KeyPropertyValue $key Version
$sp = Get-KeyPropertyValue $key SP
$install = Get-KeyPropertyValue $key Install
if($sp)
{
"$($_.PSChildName) $name SP $sp"
}
else{
"$($_.PSChildName) $name"
}
}
function Get-FrameworkVersion{
dir "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\" |? {$_.PSChildName -like "v*"} |%{
if( $_.Property -contains "Version")
{
Get-VersionName $_
}
else{
$parent = $_
Get-ChildItem $_.PSPath |%{
$versionName = Get-VersionName $_
"$($parent.PSChildName) $versionName"
}
}
}
}
$v4Directory = "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"
if(Test-Path $v4Directory)
{
$v4 = Get-Item $v4Directory
$version = Get-KeyPropertyValue $v4 Release
switch($version){
378389 {".NET Framework 4.5"; break;}
378675 {".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2"; break;}
378758 {".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2"; break;}
379893 {".NET Framework 4.5.2"; break;}
{ 393295, 393297 -contains $_} {".NET Framework 4.6"; break;}
{ 394254, 394271 -contains $_} {".NET Framework 4.6.1"; break;}
{ 394802, 394806 -contains $_} {".NET Framework 4.6.2"; break; }
}
}
It was written based on How to: Determine Which .NET Framework Versions Are Installed. Please use THE Get-FrameworkVersion() function to get information about installed .NET framework versions.
Using the Signum.Utilities library from SignumFramework (which you can use stand-alone), you can get it nicely and without dealing with the registry by yourself:
AboutTools.FrameworkVersions().ToConsole();
//Writes in my machine:
//v2.0.50727 SP2
//v3.0 SP2
//v3.5 SP1
See How to: Determine Which .NET Framework Versions Are Installed (MSDN).
MSDN proposes one function example that seems to do the job for version 1-4. According to the article, the method output is:
v2.0.50727 2.0.50727.4016 SP2
v3.0 3.0.30729.4037 SP2
v3.5 3.5.30729.01 SP1
v4
Client 4.0.30319
Full 4.0.30319
Note that for "versions 4.5 and later" there is another function.
In Windows 7 (it should work for Windows 8 also, but I haven't tested it):
Go to a command prompt
Steps to go to a command prompt:
Click Start Menu
In Search Box, type "cmd" (without quotes)
Open cmd.exe
In cmd, type this command
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get version
This gives the latest version of NET Framework installed.
One can also try Raymond.cc Utilties for the same.

NoSuchMethodError when running JMockit

I am trying to use JMockit so that I can Mock out a final method in a 3rd party jar file.
When I tried a very simple test I got the the com.sun.tools.attach.AttachNotSupportedException and after some searching around I found here that this is caused by the IBM JDK6.0 not supporting the Attach feature, and then it was suggested that the fix was to put this in my VM args:
-javaagent:C:/jars/jmockit.jar
When I did this, and re-ran, I then get the below exception.
java.lang.NoSuchMethodError: org/junit/runner/Description.getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
at mockit.integration.junit4.internal.RunNotifierDecorator.fireTestRunStarted(RunNotifierDecorator.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at mockit.internal.util.MethodReflection.invokeWithCheckedThrows(MethodReflection.java:95)
at mockit.internal.annotations.MockMethodBridge.callMock(MockMethodBridge.java:76)
at mockit.internal.annotations.MockMethodBridge.invoke(MockMethodBridge.java:41)
at org.junit.runner.notification.RunNotifier.fireTestRunStarted(RunNotifier.java)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:48)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I am using JUnit4, and the JRE which comes with RAD8.5 for Websphere 8.5 development which is the IBM JRE6.0. Here are the exact JVM details:
C:\IBM\WebSphere\AppServer\java\jre\bin>.\java -version
java version "1.6.0"
Java(TM) SE Runtime Environment (build pwa6460_26sr3-20120810_01(SR3))
IBM J9 VM (build 2.6, JRE 1.6.0 Windows 7 amd64-64 20120809_118944 (JIT enabled, AOT enabled)
J9VM - R26_Java626_SR3_20120809_1152_B118944
JIT - r11.b01_20120808_24925
GC - R26_Java626_SR3_20120809_1152_B118944
J9CL - 20120809_118944)
JCL - 20120713_01
My code is a simple empty test and so far does not use any of the features of JMockit. Here it is:
public class TestJMockit {
#Test
public void testJMockit() {
boolean isTrue = true;
assertTrue(isTrue);
}
}
I am using version 1.2 of the jmockit.jar file which is the latest version at the time of writing this.
Does anyone know if it is possible at all to use JMockit on an IBM version of a JRE or is it simply impossible?
Has anyone else encountered this error before and know of a fix for it?