Friday 23 September 2016

Maven Error When Executed Using Eclipse - No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

One may see following error for the first time when maven project is tried to be run using POM -

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Json: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Problems is about setting JRE version in eclipse/setting javac in POM.

To fix the eclipse to run Maven test -

1. Go to Installed JREs in following way through Eclipse Menu options
Menu ->Windows->Preferences->Installed JREs.

2. Select/Add Installed JRE

Another Approach -
To fix the POM - Set Maven-compiler-plugin

Reference -
http://maven.apache.org/plugins/maven-compiler-plugin/examples/compile-using-different-jdk.html

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.apache.maven.plugins</groupId>
  5. <artifactId>maven-compiler-plugin</artifactId>
  6. <version>3.5.1</version>
  7. <configuration>
  8. <verbose>true</verbose>
  9. <fork>true</fork>
  10. <executable><!-- path-to-javac --></executable>
  11. <compilerVersion>1.3</compilerVersion>
  12. </configuration>
  13. </plugin>
  14. </plugins>
  15. </build>

Some times, in-appropriate testng version causes issue.
For example I got following issue with 6.9.13.6 -

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project Json: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test failed: The forked VM terminated without saying properly goodbye. VM crash or System.exit called ? -> [Help 1]

The complete stack trace was - 
org.apache.maven.surefire.util.SurefireReflectionException: java.lang.reflect.InvocationTargetException; nested exception is java.lang.reflect.InvocationTargetException: null
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.apache.maven.surefire.testset.TestSetFailedException: Unknown TestNG version 6.9.13.6
at org.apache.maven.surefire.testng.TestNGExecutor.getConfigurator(TestNGExecutor.java:207)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:72)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:110)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:106)
... 9 more

Solution - 
TestNG version 6.9.9 worked well for me.

Monday 19 September 2016

Why Sometimes Visual Studio IDE compiles Code But MSBuild Throws Compilation Error Because Of Assembly Reference Not Found


1. I had a CodedUI Test which used CodedUI library such as -
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;

I was successfully able to compile the entire solution using Visual Stduio IDE 2013 Ultimate.
But, while I was trying to compile the same using MSBuild tool, I was getting errors because of not able to find assemblies
Following errors were thrown:
05:44:41 FunctionalTests\CodedUITest1.cs(7,40): error CS0234: The type or namespace name 'UITesting' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?) [C:\Users\Administrator\.jenkins\workspace\Bodycote\AutomatedTest\AutomatedTest.csproj]
05:44:41 FunctionalTests\CodedUITest1.cs(9,40): error CS0234: The type or namespace name 'UITest' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)

Solution - 
This error appears, when MSBuild does not find references added to project of specific version. 
Visual studio facilitates to go with any version of references. 
To go with any available reference, not to be very much strict about particular version, we have to set the property - "Specific Version" to false for used references. By default its true.

By setting Specific Version for all references to false, I solved the issue. MSBuild tool started compiling.








Sunday 18 September 2016

C# Vs Java

My experience with C# after working with Java for almost 5 years is :

1. Until Java 1.8, most of advanced features available in other languages such as C# were missing.

C# features that stand out because of coding experience -
1. Lambda/LINQ (Available in Java 1.8)
2. Extension Methods ( Its awesome feature where existing classes which can not be accessed because they may belong to .Net library/third party library, can be introduced with additional new methods, without touching its code. Surprised, why java did not have this feature. Coming from Java background, makes me little strange, even sealed classes are allowed to be extended in some way through Extension Methods)

Example :
static class Extension
{

     public static String substr(this String str, int startIndex, int lastIndex)
    {
          return str.substr(startIndex,lastIndex)
     }
}

3. Detecting DataType during compilation time using var in C#
4. optional parameter by setting default value to certain parameter in C#
5. Properties for getter/setter ; Example = public string Name {get;set;}. Here get/set can be controlled. If set is not defined, then Name becomes readonly. No need for methods like GetName(), SetName(String name);
6. out parameter
7. By default methods can not be overridden (Non Virtual). Explicit use of virtual/overridden to make method overridden. [I don't feel this is good feature. By default methods should be overridden, if a class is inherited. Java does not have concept of keywords virtual which will then allow method to be overridden, though annotation @override is possible for sake of clarity ]
8. nullable datatype ;
example - int ? x = null; provides property Value to access value. Also, HasValue will let one know, if x is assigned to some value or not assigned.


I really find coding experience in C# much better than Java. Having said that, I also like to make a point, languages that come later always know the shortcomings and come with its handling to overcome known limitation/shortcomings.
That is the case with C#, which is inspired by Java and took birth to compete with Java.
On other side, Java is opensource, very much popular, has large community, technology stack is hard to beat. Most of applications are built upon Java. Next thing is unbeatable - It's platform support/cross platform. Write once, run on many different Operating Systems.

Friday 16 September 2016

Running Groovy From Jenkins And Reading/Updating Jenkins Parameters Set Using Active Choice Parameters Plugin

Running Groovy In Jenins -

1. Need to install Groovy plugin.
2. Update Global Tool Configuration For Groovy to set path -
in my case, it is - C:\Program Files\groovy-2.4.7
Note - its not upto bin
3. add jars to groovy lib folder - jenkins-core-2.7.4.jar,stapler-1.243.jar,commons-lang-2.6.jar
jenkins-core-2.7.4.jar,stapler-1.243.jar are available in jenkins under
{User folder}\.jenkins\war\WEB-INF\lib

commons-lang-2.6.jar can be downloaded from maven.

Run groovy script as build step - Execute System Groovy Script

Reading/Updating Jenkins Parameters
Reference -
http://stackoverflow.com/questions/10882515/how-to-retrieve-jenkins-build-parameters-using-the-groovy-api
https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

My problem statement -
1. I had active choices parameters for MSTest TestCategory to execute. Like - Sanity,Smoke,Regression
2. Active Choices parameters sets parameter as - Sanity,Smoke,Regression.
3. MSTest TestCategory switch needs in Sanity|Smoke if one needs to execute tests from Sanity and Smoke Category on.
4. So, I need to reset TestCategory Parameter used for

Following was my solution -

import hudson.model.*

def testCategory = build.buildVariableResolver.resolve("TestCategory")
testCategory = testCategory.replaceAll(',','|')

def pa = new ParametersAction([
  new StringParameterValue("TestCategory", testCategory)
])

// add variable to current job
Thread.currentThread().executable.addAction(pa)







How to: Group and Run Automated Tests Using Test Categories


[TestCategory("Nightly"), TestCategory("Weekly"), TestCategory("ShoppingCart"), TestMethod()]
public void DebitTest()
{
}

To run tests that are assigned to the "Nightly" category, run the VSTest.Console.exe using the /TestCaseFilter option, or from MSTest.exe by using the /testcontainer and the /category options:
VSTest.Console.exe
Vstest.console.exe myTestProject.dll /TestCaseFilter:TestCategory=Nightly
MSTest.exe
mstest /testcontainer:MyTestprojectName.dll /category:"Nightly"
You can only use the /category option one time per command line, but you can specify multiple test categories with the test category filter. The test category filter consists of one or more test category names separated by the logical operators '&', '|', '!', '&!'. The logical operators '&' and '|' cannot be used together to create a test category filter.
For Example:
  • /category:group1 runs tests in the test category "group1".
  • /category:"group1&group2" runs tests that are in both test categories "group1" and "group2." Tests that are only in one of the specified test categories will not be run.
  • /category:"group1|group2" runs tests that are in test category "group1" or "group2". Tests that are in both test categories will also be run.
  • /category:"group1&!group2" runs tests from the test category "group1" that are not in the test category "group2." A test that is in both test category "group1" and "group2" will not be run.

How To Allow Jenkins To Publish ExtentReport Or Any Html Based Report Compromising Security

By default, Jenkins latest version displays Extent Report in normal text, as Extent Report contains scripts which pose threat to web security.

To overcome the problem, we have to override property - hudson.model.DirectoryBrowserSupport.CSP

Following way of overriding solves the problem-
java -Dhudson.model.DirectoryBrowserSupport.CSP="" -jar jenkins.war

MSTest Attributes Comparison With TestNG Test Attributes

using Microsoft.VisualStudio.TestTools.UnitTesting;
using SampleClassLib;
using System;
using System.Windows.Forms;

namespace TestNamespace
{
    [TestClass()]
    public sealed class DivideClassTest
    {
        [AssemblyInitialize()] //Before All Tests Across All Test Classes are run, mimics BeforeSuite in TestNG
        public static void AssemblyInit(TestContext context)
        {
            MessageBox.Show("AssemblyInit " + context.TestName);
        }

        [ClassInitialize()]//Before All Tests in Test Class is run, mimics BeforeClass in TestNG
        public static void ClassInit(TestContext context)
        {
            MessageBox.Show("ClassInit " + context.TestName);
        }

        [TestInitialize()] //Before Each Test Is Run, mimics BeforeTest in TestNG
        public void Initialize()
        {
            MessageBox.Show("TestMethodInit");
        }

        [TestCleanup()] //After Each Test Is Run, mimics AfterTest in TestNG
        public void Cleanup()
        {
            MessageBox.Show("TestMethodCleanup");
        }

        [ClassCleanup()] //After All Tests In Test Class are executed, mimics AfterClass in TestNG
        public static void ClassCleanup()
        {
            MessageBox.Show("ClassCleanup");
        }

        [AssemblyCleanup()] //After All Tests Across All Test Classes are executed, mimics AterSuite in TestNG
        public static void AssemblyCleanup()
        {
            MessageBox.Show("AssemblyCleanup");
        }

        [TestMethod()] //Test Method To Be Executed, mimics Test in TestNG
        [ExpectedException(typeof(System.DivideByZeroException))]
        public void DivideMethodTest()
        {
            DivideClass.DivideMethod(0);
        }
    }
}

Thursday 15 September 2016

MSTest Options

running MSTest from commandline:
https://msdn.microsoft.com/en-us/library/ms182486.aspx

General Command Line Options
/testcontainer:[file name]
Load a file that contains tests.
Example: /testcontainer:tests.dll 
For more information, see /testcontainer.
/testmetadata:[file name]
Load a file that contains test metadata. For more information, see /testmetadata.
/testlist:[test list path]
Specify the test list, as specified in the metadata file, to be run. For more information, see /testlist.
/category:[test category filter]
Specify and filter which test categories to run. For more information, see /category.
/test:[test name]
Specify the name of a test to be run. For more information, see /test.
/noisolation
Run tests within the MSTest.exe process. This choice improves test run speed but increases risk to the MSTest.exe process.
/testsettings: [file name]
Use the specified test settings file.
Example: /testsettings:Local.Testsettings
For more information, see /testsettings.
/runconfig:[file name]
Use the specified run configuration file.
Example: /runconfig:localtestrun.Testrunconfig
For more information, see /runconfig.
System_CAPS_noteNote
This command-line option is maintained for compatibility with previous versions of Visual Studio. Test run configurations have been replaced by test settings in Visual Studio Enterprise.
/resultsfile:[file name]
Save the test run results to the specified file.
Example: /resultsfile:testResults.trx
For more information, see /resultsfile.
/detail:[property id]
Specify the name of a property that you want to show values for, if any, in addition to the test outcome. For more information, see /detail.
/help
Display the MSTest.exe usage message (short form: /? or /h).
/nologo
Display no startup banner and copyright message.
/usestderr
Use standard error to output error information.

Automating dropdowns/lists

Selecting Item/Items in ListBox:
3 Possbile Methods exposed by Select Class:
1. SelectByText
2.SelectByValue
3.SelectByIndex