Automatically add properties when running JUnit in Eclipse - eclipse

In order to run my unit tests on my Eclipse, I need to set some properties for the VM.
Thus, when I first run my JUnit test, I go in "Open Run Dialog", then in my JUnit configuration for this test, I go in "Arguments" tab and put everything I need in the "VM arguments" text area.
Is there a way to automatically add a set of properties when I run my JUnit, so I will be able to only right-click on the test class, and click on "Run as > Junit Test" to run a test?
Technical information:
Eclipse 3.3.2, JUnit 4, Java 5
Edit, regarding response from Aaron Digulla:
These properties are used in Spring configuration files*. Thus, I can't use the idea given by Aaron, as Spring will be initialized before the test is run.
In addition to that, I just need to know if I can achieve that in a easy way in Eclipse. Thus the solution must not have any impact on the compilation of the application outside Eclipse, as my application will finally be compiled (and tested) by Maven2.
* few "unit" tests indeed need my Spring configuration to be run. Ok, I know that it is not real unit tests ;o)
Edit 2: In fact, I was indeed starting the Spring configuration by a test unit. Thus, before starting Spring, I check the System properties, and if my properties are not set, then I give them the required value...
However, I am a little disappointed that Eclipse can't do that for me automatically...

You could try this - go to
Window->Preferences->Java->Installed JREs
ans select the JVM in use, than put a "Default VM" prameter like
-DrunningInEclipse
Than you can check from within your TestCase:
System.getProperty("runningInEclipse") != null

My solution is to create an abstract test base class for all tests in a project which extends TestCase. It has to be abstract so the automatic unit test finder will not consider it.
In static code block of this class, I set all properties I need. This ensures that the code runs once and only once and that it runs before any test in my project.
[EDIT] You say that Spring is initialized before the tests run. This is a bug in your project: It must be the tests who initialize Spring. Otherwise, you will always run into the problem that you have to test something outside of your control.
Therefore, I suggest to move the Spring init code into a place where you can call it at the point in time when the environment is ready.
Alternatively, check that the environment is correctly set up in setUp() and throw an error if a property is missing. This way, you will at least know why the tests would fail later. But I still prefer to have total control when which subsystem comes to life. Anything else just begs for disaster.

When i want to set some properties entries for my junit test i implement the following
protected void setUp() throws Exception {
super.setUp();
System.setProperty("Property1", "value1");
System.setProperty("Property2", "value2");
}
The properties are set before the test methode is called
EDIT:
You also can read the properties from a file and at thes to the System properties

I never understood why the launch configurations have a way to define environment variables but the only way of adding a system property seems to be to add vm arguments.
The way I've worked around this is to have tests (or an abstract tests base class) test for the presence of required properties, if they aren't there then I load them from a .properties file on the classpath.
This works as I can still override them or specify them from ANT or Maven but can also 'right click' -> Run As -> Junit Test the individual test files.
edit: here is an example of getting Spring to optionally load a properties file in the same manner as described above:
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="database.properties"/>
<property name="ignoreResourceNotFound" value="true" />
<property name="systemPropertiesMode">
<util:constant static-field="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</property>
</bean>

Agreed used method in this way in one of my junit tests and it worked
#BeforeClass
public static void setupProperties() {
System.setProperty("catalina.base", "C:\\sam-tomcat-7.0.42");
}

Related

NUnit TestDirectory wrong when running tests from multiple TestProjects in NUnit Runner

I'm using VS 2013 and NUnit.
I'm running my tests in Resharpers's TestRunner GUI - this thing:
I have multiple projects (Solution.Foo, Solution.Bar, etc), and tests for each project in Solution.Foo.Tests, Solution.Bar.Tests, etc.
One of my tests in Foo.Tests is accessing a file, located in the Solution.Foo.Tests Folder.
I use TestContext.CurrentContext.TestDirectory to locate it and when I run that test it all works just fine.
If I run the whole suite of tests in Foo.Tests, (i.e. click on Solution.Foo.Tests in the Runner GUI and run) then it's fine.
But if I select one test from Bar.Tests and my file-reading test from Foo.Tests, then it fails, because suddenly TestDirectory is set to a path in Bar.Tests.
It's as if NUnit set TestDirectory once when it starts running a collection of tests, determined by where the first test is and then never updates it again.
Any ideas what's going on and how to fix it?
ReSharper has an optimisation for speed, by sharing an AppDomain across multiple assemblies. The downside to this is that it will pick an arbitrary assembly to be the main one, which means the directory can be wrong (and it might not pick up the correct app.config, too).
You can disable the optimisation in ReSharper → Options → Unit Testing, by checking the "Use separate AppDomain for each assembly with tests".

Set openejb javaagent in code?

I'm currently writing integration tests for a Java EE application and use openejb/openjpa.
But as I'm using CMP I have to use a javaagent to enhance my classes. In maven I can configure my surefire plugin to do this enhancement, or better set the agent as vm parameter to the test.
But as I'm currently developing I like to run my tests quite often in eclipse. But there I don't want to set the agent all the time via
java -javaagent:openejb-javaagent-4.6.0.jar _\[other params...](other-params....html)
Does someone have a useful solution for this problem?
For testing in Eclipse purposes, I always create a variable that can be used in the VM arguments section of your Run Configuration. This way all you need to specify is something like ${agent} (or whatever you call it) rather than the full javaagent string.
Mhh but not sure, looking at my properties, my classes should be enhanced at runtime:
#Before
public void startupContainer() throws NamingException {
Properties p = new Properties();
p.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
p.put("openjpa.jdbc.DBDictionary", "hsql(SupportsSelectForUpdate=true)");
p.put("openejb.embedded.initialcontext.close", "destroy");
p.put("openjpa.RuntimeUnenhancedClasses", "supported");
p.put("openjpa.DynamicEnhancementAgent", "true");
p.put("javax.persistence.lock.timeout", "0");
p.put("openejb.log.factory", "slf4j");
ejbContainer = EJBContainer.createEJBContainer(p);
}

Is there Any Way to Enforce RuntimeUnenhancedClasses in EE Configuration

I just spent a half hour debugging some new code that's not broken because I forgot to check (again!) my logs for this dreaded message:
WARN openjpa.Enhance - Creating subclass for ...
I'm running OpenJPA 2.1.0 inside an OpenEJB 3.2 snapshot build, Java 1.6.0_25, and Eclipse Helios. My entities are enhanced using the ant PCEnhancerTask.
My META-INF/openjpa.xml contains
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
<property name="openjpa.DynamicEnhancementAgent" value="false" />
Is there anyway with this EE configuration to have OpenJPA enforce the RuntimeUnenhancedClasses option as it does in an SE configuration?
I suspect my 'real' problem stems from an Eclipse svn update that sometimes touches my JPA entity source, causing a build that overwrites my enhanced classes.
It's frustrating how often I run a unit test from the IDE that fails in some weird way, and I go digging through my code looking for a problem when all I need to do is run the enhancer.
Put the <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" /> META-INF/persistence.xml.
Looks like we're logging this action on debug level (maybe it should be info level), but OpenEJB will set that property to the default as it was in OpenJPA 1.x so that apps that worked with OpenEJB 3.1.x/OpenJPA 1.x will still work without modification in 3.2.x. If the property is already set in the persistence.xml it will never be overridden, so setting it there will have the effect you want.
Open to suggestions on how to save others in the same boat some time in the future. Seems either looking in the openjpa.xml file and seeing the property set already or issuing the log message on info would do it -- or both.
It sounds like for whatever reason your properties aren't being picked up when running in the container.
I have a number of possible solutions:
Try setting your properties in META-INF/persistence.xml. I assume you have these properties in the openjpa.xml file for a reason, but it might help us figure out where the real problem is.
Set -Dopenjpa.RuntimeUnenhancedClasses=false as a JVM property. This will apply to all PUs for a given JVM.
Move to a version of OpenJPA that is >= 2.0.0. RuntimeUnenhancedClasses was turned off as the default behavior in that release.

java.lang.exception no runnable methods junit

I have a suite, inside which I have added the test class.
I am using surefire to run my JUnits.
My test class ends with test and the methods has #test annotations to it.
How can this problem be resolved?
Here are various suggestions for this incomplete question (for those unfortunate enough to be brought here by google looking for an answer to this common issue):
if using Junit4.x, just use annotations (#Test); don't create a test suite: see this question for details.
original question said "#Test" annotation is being used, which should prevent the error. But it can still happen if there are other errors that happen earlier, and junit can hide the original problem with this message. E.g., see if there are problems with Spring configuration (unset #Required attributes), misconfigured mock objects, etc.
to avoid other frequent issues that also may generate this error (such as running classes suffixed by "*Test" that do not have any #Test methods), try updating to the surefire plugin 2.7 (currently #2.8.1) and junit 4.7+ (currently #4.8.1) to avoid this issue (i'm using maven3, btw; perhaps do a "mvn clean" before "mvn test" to be safe)
long shot: upgrade to at least ant 1.7+ (currently 1.8+) to avoid junit 4 test suite issues
You are using the correct version of JUnit at least 4.X to be able to use annotations for that? (Maven?)

How to report the progress when NUnit tests crashes on a CruiseControl.NET server?

Nunit works quite well with CruiseControl.NET, but there is one thing that irritates me a lot.
If there is a test that causes Nunit to crash, I would only get little information about the crash because the XML report of Nunit doesn't get a chance to be created and be merged into the CruiseControl report.
I need a way to report the progress even when Nunit crashes during the execution.
I have been tried to force each test to output some information to the console to resolve this problem. I have thought about using SetUp method, but I haven't found any good way to get the name of the current running test.
I think a better answer would be to create an NUnit Add-in that implements EventListener interface to capture the TestStarted event to output the progress to the console or a file.
The EventListener interface is documented on NUnit website: http://nunit.org/index.php?p=eventListeners&r=2.5
In addition, we can make the Dashboard report better even when NUnit crashes during its execution. We can use the following procedure to ensure that the DashBoard always shows something about the tests.
Run tests with the EventListener which outputs the progress to a separate file
After running tests, use another program to check the file
If the file does not contain a specific "end line", generate a special XML report based on the file and merge it into the CruiseControl log
If getting the name of the current running test is what you're after you could grab it with the following:
using System.Diagnostics;
...
[Test]
public void SomeTestThatWillCrash()
{
StackFrame sf = new StackFrame();
Console.WriteLine("Now running method: " + sf.GetMethod().Name);
...
}
CruiseControl.net recommends that you use NUnit through your builder (i.e. NAnt/MSBuild). See here: http://confluence.public.thoughtworks.org/display/CCNET/NUnit+Task. As they describe - it will allow you to run these tests locally first - which should give you an exception that you can clear up.
That being said - are your developers running these unit tests prior to checking in code? That could ease this issue. If its an integration issue - I would suggest grabbing the latest code base and running the tests locally to see what is out of sorts.
I don't know if NUnit is able to create the results file even when it crashes. Even if it did - you could run into problems if that file is not well formed due to the crash.
You could use #jpoh's approach but do it in the TestSetup method which would require you do it per-fixture. If really needed, you could write a base class that all your test fixtures inherit from that implement this method.
Another solution is to use MSBuild to run NUnit and use the task in the MSBuildCommunityTasks library. This allows you to continue on error and also get the error code back from NUnit. You won't get what method caused the problem, but might help some. Here is my MSBuild target:
<Target Name="UnitTest"
DependsOnTargets="BuildIt">
<NUnit Assemblies="#(TestAssemblies)"
ToolPath="$(NUnitx86Path)"
WorkingDirectory="%(TestAssemblies.RootDir)%(TestAssemblies.Directory)"
OutputXmlFile="#(TestAssemblies->'%(FullPath).$(NUnitFile)')"
Condition="'#(TestAssemblies)' != ''"
ExcludeCategory="$(ExcludeNUnitCategories)"
ContinueOnError="true">
<Output TaskParameter="ExitCode" ItemName="NUnitExitCodes"/>
</NUnit>
<!-- Copy the test results for the CCNet build before a possible build failure (see next step) -->
<CallTarget Targets="CopyTestResults" Condition="'#(TestAssemblies)' != ''"/>
<Error Text="Test error(s) occured" Code="%(NUnitExitCodes.Identity)" Condition=" '%(NUnitExitCodes.Identity)' != '0' And '#(TestAssemblies)' != ''"/>
</Target>
This probably won't fit your needs as is, but is something to try out and play with.
That said, I would agree with #rifferte that it sounds like you need to debug the problem locally and not rely on CC.NET to handle the reporting.