Junit #value annotated field usage Java - junit4

what if I need to give two different values for a #Value annotated field in a Junit test class. Here I have a boolean field which is #Value annotated. so I have to write Junit testcase for scenarios where it can be true as well as false.
I have used #TestPropertySource(properties = "underwriting.skip=true").
for the below field
#Value("${underwriting.skip}")
protected Boolean skipUnderwriting;
But to test some code, I need to make the value false at some point. Pls suggest.

You can have different #TestPropertySource annotations for different test classes. Depending on your needs, you can have #TestPropertySource(properties = "underwriting.skip=true") on some tests and #TestPropertySource(properties = "underwriting.skip=false") on others.
(Note: The #TestPropertySource belongs on your test class, not on the actual class.)

The below solution worked for me. I used ReflectionTestUtils to set value to property field in each test case method.
ReflectionTestUtils.setField(classToTest, "skipUnderwriting", Boolean.TRUE);

Related

Hibernate Search - StandardAnalyzer with empty stopwords via persistence.xml

I've a question regarding the configuration of Hibernate Search via persistence.xml . The standard analyzer used for indexing and searching is the StandardAnalyzer. This analyzer has a list of english stopwords per default. I know that via constructor this stopword-list can be replaced with an own list (or EMPTY_SET). Unfortunately I didn't find such an option in the official documentation. The only thing I found is that it's possible to set a different analyzer via the hibernate.search.analyzer property. My question: is there an existing property to deactivate the english stopwords while using the StandardAnalyzer?
You could define your own subclass of StandardAnalyzer, pass the parameters you want to the super constructor, and set the hibernate.search.analyzer property to the fully qualified classname of your subclass. EDIT: As #AnarchoEnte replied, StandardAnalyzer is a final class, so you actually cannot do that.
But in my opinion, you'd be better off defining your own analyzer doing exactly what the standard analyzer does, but without stopwords:
#AnalyzerDef(
name = "myDefault",
tokenizer = #TokenizerDef(
factory = org.apache.lucene.analysis.standard.StandardTokenizerFactory.class
),
filters = {
#TokenFilterDef(
factory = org.apache.lucene.analysis.standard.StandardFilterFactory.class
),
#TokenFilterDef(
factory = org.apache.lucene.analysis.core.LowerCaseFilterFactory.class
)
}
)
public class MyEntity { // The annotation must be on an indexed entity, which one doesn't matter.
...
}
Then set it as default analyzer:
hibernate.search.analyzer = myDefault
This way, if you ever need to change something to the analyzer (add some filters, change the tokenizer, ...) you will only have to change that definition.

TestNG IAnnotationTransformer2 transformed value reverts to default

In summary, my implementation of IAnnotationTransformer2 picks up a test method annotation and modifies it successfully, along with all other method annotation transformations. Then at test execution time, the annotation value reverts to the hardcoded value, but only for the one method, not for any others. The other methods use the transformed values successfully.
Details:
I have a TestNG test class ServiceTest with a number of test methods (>25).
I also have a custom annotation #QueryFile which takes a list parameter containing an array of String which reference paths to text files containing parameters:
//ServiceTest.java snippet, original:
#Test (dataProvider="QueryTests",groups={"json","api"})
#QueryFile(list={
"/test/inserts_multiquery_json.txt",
"/test/selects_multiquery_json.txt"
})
public void testWithMultipleQueries(String query) throws...
Previously, as in the example above, the list values were hard-coded into the ServiceTest class, with a separate set of paths for each method.
Recently, I have added a implementation of IAnnotationTransformer2, QueryFileTransformer, to load these paths from a properties file instead. This makes the job of toggling test parameters on and off significantly easier (e.g., I can just rename various versions of the properties files to the expected name and it gets picked up.)
Revised ServiceTest.java
// revised ServiceTest.java snippet:
#Test (dataProvider="QueryTests",groups={"json","api"})
#QueryFile(list={})
public void testWithMultipleQueries(String query) throws...
...
#Test (dataProvider="QueryTests",groups={"json","api"})
#QueryFile(list={})
public void testWithJSONParams(String query) throws...
TestNG_toggle.properties
// TestNG_toggle.properties snippet:
# General tests
testWithMultipleQueries=\
/test/inserts_multiquery_json.txt,\
/test/selects_multiquery_json.txt,\
/test/updates_multiquery_json.txt,\
/test/deletes_multiquery_json.txt
testWithJSONParams=\
/test/inserts_multi_json.txt,\
/test/selects_single_json.txt,\
/test/selects_multi_json.txt,\
/test/updates_single_json.txt
So here's the problem: One of my test methods, and only one, suffers the indignity of reverting to its default #QueryFile annotation value during test execution. All other methods honor the annotation value resulting from QueryFileTransfomer.transform. In the example above, testWithJSONParams executes correctly with the values from the properties file, but testWithMultipleQueries executes with a null list, and is skipped. When testWithMultipleQueries has a hardcoded list, it works fine.
Some facts:
Execution is through maven surefire and failsafe
preserve-order="true"
as stated above: QueryFileTransformer picks up the testWithMultipleQueries annotation and modifies it successfully, in the midst of all other transformations. Then at test execution time, the annotation value appears to revert to the hardcoded value.
stepping through the eclipse debugger, it seems the transformation of testWithMultipleQueries occurs earlier than other method annotation transformations, but it's not always first. Often it is intermingled with methods from other classes, which are listed first in the xml file, whereas the rest of the ServiceTest methods seem to transform in sequence.
Specifying the method as exclusive in the xml config file had no impact other than the expected of omitting the other methods' execution.
UPDATE Further debugging implies the instance the test method passed to the DataProvider (and it's declared annotations) is a different instance than the one with transformed annotations. This is not the case with the methods that succeed.
Any insight you can provide will be most helpful.
Thanks!

validating that a field is unique using Bean Validation (or JSF)

I have an simple object that has a name
public class Foo {
private String name
}
Each user on the site may have up to 10 Foo's associated with them. Within this context, when a new Foo is created, I would like to validate that there isn't another foo associated with the same user that already exists.
I could Create a custom Bean Validator But annotations require the paramaeters to be defined during compilation. How would I then pass across the names of the existing Foos?
As suggested in various places, I could use EL expressions as an alternative way to pick up the data. This feels like using a sledgehammer to crack a nut. It also brings in a whole bunch of potential issues to consider least of all being ease of testing.
I could do class-wide validation using a boolean field
#AssertTrue(message="Name already exists")
public boolean isNameUnique() {
return (existingNames.contains(name));
}
But the validation message would not show up next to the name field. It is a cosmetic issue and this can be a backup plan. However, its not ideal.
Which brings me to the question:
Is there a simple way to write a Bean Validator that can check the value against a collection of values at the field level and meet the following restrictions ?
Previous values determined at runtime
Not using things like EL expressions
Field level validation instead of class level.
EDIT in reponse to Hardy:
The Foo class is an entity persisted within a database. They are picked up and used through a DAO interface.
I could loop through the entities but that means plugging the DAO into the validator and not to mention that the I would need to write the same thing again if I have another class that too has this constraint.
It would help to see how you want to use the Foo class. Can you extend your example code? Are they kept in a list of Foo instances. A custom constraint seems to be a good fit. Why do you need to pass any parameters to the constraints. I would just iterate over the foos and check whether the names are unique.

How to get an IType from a class name in Eclipse JDT

I'm implementing a variant of the JUnit New Test Suite Wizard, and instead of getting test classes from the current project, I need to get them from another source. They come to me as strings of fully-qualified class names.
Some of them may not yet exist in this user's workspace, let alone in the classpath of the current project. The user will need to import the projects for these later, but I don't want to mess with that in my wizard yet. I need to just add all classes to the new suite whether they exist yet or not.
For those classes that are already in this project's classpath, I can use IJavaProject.findType(String fullyQualifiedName) . Is there an analogous way to get ITypes for classes that are not (yet) visible?
I would be happy to construct an IType out of thin air, but ITypes don't seem to like being constructed.
I don't think that is possible: the Java Document Model interfaces are created based on the classpath.
Even worse, if the project do not exist in the users workspace, the resulting code would not compile, and that is another reason for not allowing the arbitrary creation of such constructs.
If I were you, I would try to help the user to import the non-existing projects in case of types are not available, thus avoiding the tackling with the Java Document Model.
For my purposes, creating a HypotheticalType and a HypotheticalMethod got the job done. I'm attaching an overview in case anyone else needs to follow this path.
First I created a HypotheticalType and had it implement the IType interface. I instantiated one of these at the proper spot in my modified wizard. Using Eclipse's Outline view I created a method breakpoint on all methods in my new class. This let me detect which methods were actually getting called during execution of my wizard. I also modified the constructor to take, as a String, the name of the class I needed the wizard to handle.
Almost all of the new methods are ignored in this exercise. I found that I could keep the default implementation (return null or return false in most cases) for all methods except the following:
the constructor
exists() - no modification needed
getAncestor(int) - no modification needed, but it might be useful to return the package of my hypothetical class, e.g. if my class is java.lang.Object.class, return java.lang.
getDeclaringType() - no modification needed
getElementName() - modified to return the class name, e.g. if my class is java.lang.Object.class, return Object.
getElementType() - modified to return IJavaElement.TYPE
getFlags() - not modified yet, but might be
getMethod(String, String[]) - modified to return a new HypotheticalMethod(name)
getMethods() - modified to return new IMethod[] { new HypotheticalMethod("dudMethod") }
In the process I discovered that I need to be able to return a HypotheticalMethod, so I created that type as well, inheriting from IMethod, and used the same techniques to determine which methods had to be implemented. These are the only methods that get called while this wizard runs:
The constructor - add a String parameter to bring in the name of the method
exists() - no modification needed
isMainMethod() - no modification needed
That covers the solution to my original question. Zoltán, I'll be doing as you suggested in an upcoming iteration and trying to assist the user in both the case in which the desired class is not yet in this project's classpath, and the case in which the desired class is in some project not yet in the workspace.

Ignore all NUnit tests in a file

I can add an attribute on a test to ignore it:
[Test]
[Ignore("Foo Bar")]
Is there a way to ignore all tests in a file (at the TestFixture level)?
[TestFixture, Ignore("reason")]
public class YourTestFixture { }
Or if you prefer to break your attributes out to one per line:
[TestFixture]
[Ignore("reason")]
public class YourTestFixture { }
As suggested, the [Explicit] attribute works well. You can also simply place the [Ignore()] attribute under the [TestFixture] attribute, as shown in the documentation:
http://www.nunit.org/index.php?p=ignore&r=2.5
Use [Ignore()] if you want the test to be flagged as ignored (and therefore you get the yellow bar if all other tests pass). Use [Explicit] if you want the test to be completely discounted (and therefore you get the green bar if all other tests pass).
You can make the whole TestFixture "on-demand" by using the [Explicit] attribute. Then it's there when you want it, but only when you explicitly click on it.
Before NUnit 2.5, removing the [TestFixture] attribute from the class seems like it would work.
This is not the case for NUnit 2.5 and later in which the [TestFixture] attribute is optional for non-parameterized non-generic fixtures. See here for more.
Simply don't apply the TextFixture attribute on the class.