Adding #Test to each method after upgarding from Junit 3.x to Junit4.x - junit4

We upgraded Junit framework from 3.x to 4.x. and In 4.x, each test method will be recognized by adding #Test annotation at top of the method.
There exists a test class with multiple test methods like test***() (around 250 methods). Do we need add #Test for each and every method? If not, what is the way to make sure all 250 run?

When I had a large number of tests to convert, I used the JUnitConverter tool. It performs the following tasks:
Adding the #Test annotation before test methods.
Adding the #Before annotation before the setUp() method.
Adding the #After annotation after the tearDown() method.
Adding a static import for adding the different assert() methods.
It's not 100% perfect, IIRC, but it does a lot of the work automatically. I used it to convert Apache Commons Lang from JUnit 3 to JUnit 4 some years ago.

Related

What is the difference between testng annotation #Beforemethod and beforeinvocation() listener?

Does #Beforemethod() and beforeInvocation() listener do the same? Please help with the difference!
#Beforemethod: The annotated method will be run before each test method meaning Methods annotated with #Test annotation
If you have implemented the IInvokedMethodListener listener
void beforeInvocation(IInvokedMethod method, ITestResult testResult)
void afterInvocation(IInvokedMethod method,ITestResult testResult)
then IInvokedMethodListener will be invoked for configuration(#BeforeSuite...) and test methods (#Test ...).
From an execution stage perspective, both get executed before a method annotated with #Test is called. It allows you to do any kind of setup you need for a test.
But when do you use what will be based on what is it you want to do.
If you have a specific setup for only a few tests, I will use #BeforeMethod in a class which would apply only to a few tests.
But if it is an suite wide setup, say initializing a driver object or creating an API token which needs to be done for every single test in your suite, then I would prefer listeners.

What are the limitations of #Transactional in CDI?

I am trying to use a #Transactional method inside a CDI class, instead of an EJB:
#javax.inject.Named
// fails #javax.enterprise.context.ApplicationScoped
// fails #javax.enterprise.context.SessionScoped
// works #javax.ejb.Singleton
// works #javax.ejb.Stateless
public class SomeClass {
#javax.persistence.PersistenceContext
private EntityManager em;
#javax.annotation.PostConstruct
#javax.transaction.Transactional
public void someMethod() {
em.persist(someEntity);
}
}
When I annotate SomeClass with #Singleton or #Stateless, everything works.
When I annotate SomeClass with #ApplicationScoped or #SessionScoped, WildFly 13 displays the following error message:
Transaction is required to perform this operation (either use a transaction or extended persistence context)
I was under the impression that #Transactional works with CDI since Java EE 7. Have I been mistaken? Or am I simply missing some additional configuration?
I'll try to give a short list of things to look when trying to make #Transactional work with CDI, so as to give the answer a bit more value than the comment:
We are discussing javax.transaction.Transactional, not javax.ejb.TransactionAttribute, which works for EJBs!
It does NOT work out-of-the-box in non-JEE applications!
And by JEE applications we mean those running a full JEE application server; Tomcat out-of-the-box does NOT support it!
Beware of classpath problems, specifically make sure no jar containing the annotation javax.transaction.Transactional exists e.g. in WEB-INF/lib, when running in a full JEE application server. If you want to utilize it in a non-full-JEE environment, you will need to have it in the classpath.
#Transactional is implemented as a CDI interceptor by the latest JTA specifications. As such:
It's not there in JEE < 7!
It has the same limitations as any interceptor. E.g. it cannot be called for initializer methods - #PostConstruct [THIS WAS THE PROBLEM IN THIS QUESTION], and it is NOT activated when invoking methods of this object, BEWARE!!!
I am quite confident that more errors may exist!!!

Migration problems when migrate from NUnit 2.X to NUnit 3.X

I'm using NUnit 2.X library but want to use NUnit 3.X now. I have some problems about migration from 2.X to 3.X. First i have a setup fixture class. Here is the 2.X version;
using System;
using System.IO;
using System.Reflection;
using HalisEnerji.QuantSignal.Logging;
using NUnit.Framework;
namespace HalisEnerji.QuantSignal.Tests
{
[SetUpFixture]
public class Initialize
{
[SetUp]
public void SetLogHandler()
{
Log.LogHandler = new ConsoleLogHandler();
}
}
}
First problem is fixed via change "Setup" attribute with "OneTimeSetUp" attribute. Second problem fixed via add some codes for set test directory. Because i'm using Re-Sharper test engine. Here is final shape of setup fixture;
using System;
using System.IO;
using System.Reflection;
using HalisEnerji.QuantSignal.Logging;
using NUnit.Framework;
namespace HalisEnerji.QuantSignal.Tests
{
[SetUpFixture]
public class Initialize
{
[OneTimeSetUp]
public void SetLogHandler()
{
Log.LogHandler = new ConsoleLogHandler();
var assembly = Assembly.GetExecutingAssembly();
var localPath = new Uri(assembly.CodeBase).LocalPath;
var direcotyName = Path.GetDirectoryName(localPath);
if (direcotyName != null)
{
Environment.CurrentDirectory = direcotyName;
}
}
}
}
Well after solve setup fixture problem, my real problems begins with use TestCaseSource/TestCaseData. Here is sample 2.X version;
[Theory]
[TestCaseSource("CreateSymbolTestCaseData")]
public void CreateSymbol(string ticker, Symbol expected)
{
Assert.AreEqual(Symbol.Create(ticker), expected);
}
private TestCaseData[] CreateSymbolTestCaseData()
{
return new []
{
new TestCaseData("SPY", new Symbol(Security.GenerateEquity("SPY"), "SPY")),
new TestCaseData("EURUSD", new Symbol(Security.GenerateForex("EURUSD"), "EURUSD"))
};
}
2.X version creating exception and my tests are fail. Shortly exception telling that TestCaseData provider method must be static. Well, after mark method with static identifier test working correctly but this time my other test failing (before use static identifier it's not failing). Why my other test failing? Because it's reading a file from test directory and somehow test working before setup up fixture codes run and change test directory!
Before use static identifier first SetUpFixture codes run and then tests code run. After use static identifier order changing my test that read file from test directory (which is Re-Sharper's temporary directory and not contain necessary file) run first after that SetUpFixture codes run. Any idea how all my tests to be successful?
UPDATE:
Explain some units;
I have Initialize.cs (part of my test assembly) which is responsible setup CurrentDirectory.
I have Config.cs (part of my project infrastructure assembly) which is my project configuration file and it has public static readonly Setttings property which is reading configuration file from CurrentDirectory.
I have ConfigTests.cs (part of my test assembly) which is contain some test methods for read/write Settings property.
When i debug tests;
Before use any static TestCaseSource, they are working below order;
A. Initialize.cs => Setup method
B. Config.cs => static Settings property getter method
C. ConfigTests.cs => first test method
So initialize working first others working later all tests successfully passing from test.
After use static TestCaseSource for inside other test file lets say OrdersTests.cs (excluded from project for first scenario after that included again), somehow working order is changing like below;
A. Config.cs => static Settings property getter method
B. OrdersTests.cs => static TestCaseSource method (not test method)
C. Initialize.cs => Setup method
D. ConfigTests.cs => first test method
E. OrdersTests.cs => first test method
So, my ConfigTests.cs tests failing because Initialize.cs working after Config.cs. I hope with this update my problem is more clear.
Is this problem related NUnit or Resharper or V.Studio? I don't know and all i know is my successfully passing tests are failing now!
UPDATE 2:
Chris,
Yes you are right. I explore project in detail and i saw the problem is related that my project's some classes accessing to static Config class and it's static Settings property (before run test setup fixture method and even before static test case source method!). You talk about order of process of test methods; NUnit doing tests like your said, not like i said. But when i try to use your solution (set current directory before test case source) it's not working. Because of that i solve my problem in another way. I'm not happy but at least my test methods working now. Could you please tell me what are the technical reasons that run static test case methods before initialize/setup method? Is this because of NUnit or because of infrastructure of .Net Framework? I'm not fanatic about NUnit and/or TDD. I don't have deep knowledge about these concepts but it does not make sense to me: run any method before setup method.
Thanks for your interest.
Because it's reading a file from test directory and somehow test working before setup up fixture codes run and change test directory!
How are you reading this file? You should use TestContext.CurrentContext.TestDirectory to get the test directory in NUnit 3, rather than relying on the location of the current directory. See the Breaking Changes page for details.
Edit: I also see you've tagged this ReSharper 7.1. You should be aware that this version of resharper does not support NUnit 3 - the first version that did is ReSharper 10. Your tests will appear to run correctly - however you may experience weird side effects, and this may break in any future version of NUnit.
Response to update:
Take a look at NUnit 3's Breaking Changes page. There are two relevant breaking changes between NUnit 2 and 3.
TestCaseSource's must now be static.
The CurrentDirectory is no longer set to Environment.CurrentDirectory by default.
The first you've solved easily enough. The second, is what's now causing you issues.
NUnit 3 runs it's methods in this order:
Evalute TestCaseSource methods (OrdersTests.cs)
Run SetUpFixture (Initialize.cs)
Run Test (ConfigTests/OrdersTests)
I'm not sure what Config.cs is being called before your TestCaseSource method - are you sure of that order? Does anything in CreateSymbolTestCaseData() call anything in Config.cs You could try rewriting your TestCaseSource as such:
private TestCaseData[] CreateSymbolTestCaseData()
{
Environment.CurrentDirectory = "c:\RequiredDirectory";
return new []
{
new TestCaseData("SPY", new Symbol(Security.GenerateEquity("SPY"), "SPY")),
new TestCaseData("EURUSD", new Symbol(Security.GenerateForex("EURUSD"), "EURUSD"))
};
}

How to make JUnit annotations work in SOAP UI?

I am trying to port my JUnit test scripts into SOAP UI. Since SOAP UI supports Java, I thought it will support JUnit as well. I have placed the JUnit Jar in 'ext' folder. When I run the test, I could see that the annotation #Test is not being recognized by SOAP UI.
I got the below error:
Script1.groovy: 9: Invalid constructor format. Remove 'void' as the
return type if you want a constructor, or use a different name if you
want a method. at line: 9 column: 4. File: Script1.groovy # line 9,
column 4.
#Test
Am I doing it entirely wrong?
Without seeing your code (since it hasn't been posted as of writing this), you probably don't need to have a return type of void, especially on the constructor.
I'm still a little confused by your question though; are you trying to run JUnit from inside of SoapUI (it appears that way from the error message you are getting) or do you want to run it from a Java class, using JUnit and calling SoapUI. If you are doing the latter, try the following example of the format that should work:
public class CalculatorServiceTestCase {
#Test
public void testCalculatorService() throws Exception {
SoapUITestCaseRunner testCaseRunner = new SoapUITestCaseRunner();
SoapUIMockServiceRunner mockServiceRunner = new SoapUIMockServiceRunner();
testCaseRunner.setProjectFile("src/test/resources/calculator-soapui-project.xml");
mockServiceRunner.setProjectFile("src/test/resources/calculator-soapui-project.xml");
mockServiceRunner.run();
testCaseRunner.run();
}
}

Eclipse: how to update a JUnit test file with newly added method in the source file?

Using Eclipse (Helios), I could create a JUnit test file ClassATest.java of the source file ClassA.java by using New -> JUnit Test Case -> Class under test..., then choose all the methods of ClassA to be tested.
If later we add some more methods to ClassA, how do we easily reflect this addition in ClassATest ? (No copy/paste plz).
One solution is to use MoreUnit
With MoreUnit installed to Eclipse, one can right click onto the newly added method (and not yet unit tested), and choose "Generate Test"
Of course, if one always follows the writing-test-before-writing-method style, then this solution is not needed. However in reality sometimes you don't have a clear idea of what you would want to do, in that case you would have to code up some method, play with it, then rethink and code again until you are satisfied with the code and want to make it stable by adding unit test.
You should look into creating a JUnit test suite which will execute all tests within the classes you specify. Thus, adding new test cases is as simple as creating a new class and adding it to the #Suite.SuiteClasses list (as seen below).
Here's an example.
Example JUnit Test Suite Class:
#RunWith(Suite.class)
#Suite.SuiteClasses({
TestClassFoo.class
})
public class ExampleTestSuite {}
Example Test Case class:
public class TestClassFoo {
#Test
public void testFirstTestCase() {
// code up test case
}
}