How to check whether Junit is running with JunitRunner or PowermockRunner - java

During writing junits to the classes, I got some requirement like executing tests in with different runners like once with JUnitRunner and then with PowermockRunner, so based on that I want to decide whether to skip test or continue. Please could you let me know is there any way to check like this?
Thanks in advance.

There are several options, but none of them is pretty.
Your best bet would be if either of these runners supported a system property that you can query, but I doubt that.
Failing that, you can either do a class lookup or inspect the stack.
Class Lookup
boolean isPowerMock = false;
try{
Class.forName("fully.qualified.name.of.PowerMockRunner");
isPowerMock = true;
}catch(ClassNotFoundException e){}
Note that this technique may return a false positive if PowerMock is on the class path, but the runner isn't used.
Inspect stack
boolean isPowerMockRunner = false;
for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
if(stackTraceElement.getClassName().contains("PowerMockRunner")) {
isPowerMockRunner = true;
break;
}
}
Or, Java 8-style:
boolean isPowerMock = Arrays.stream(
Thread.currentThread()
.getStackTrace()
)
.anyMatch(
elem -> elem.getClassName()
.contains("PowerMockRunner")
);

Related

Which is the best way to set/drop boolean flag inside lambda function

Say I have a currency rates loader returning isLoaded=true result only when all the rates are loaded successfully:
//List<String> listFrom = Stream.of("EUR", "RUB").collect(toList());
//List<String> listTo = Stream.of("EUR", "CNY").collect(toList());
boolean isLoaded = true;
final FixerDataProvider httpProvider = new FixerDataProvider(maxAttempts);
final List<CurrencyRatePair> data =
listFrom.stream()
.flatMap(from -> {
final List<CurrencyRatePair> result = httpProvider.findRatesBetweenCurrencies(from, listTo);
if (Objects.isNull(result) || result.size() == 0) {
isLoaded = false; //!!!Not working as ineffectively final!!!
}
return result.stream();
}).collect(Collectors.toList());
if (!isLoaded) {
return false;
}
// do smth with loaded data
return true;
Assignment isLoaded = false; inside lambda function is not allowed when isLoaded variable is not final or effectively final.
Which is the most elegant solution to set/drop boolean flag inside lambda expressions?
What do you think about AtomicBoolean and set(false) method as a possible approach?
You may be better off with an old-style loop, as others have suggested. It does feel like a bit of a programming faux pas to write lambdas with side-effects, but you're likely to find an equal number of developers who think it's fine too.
As for getting this particular lambda-with-side effects working, making isLoaded into an AtomicBoolean is probably your best bet. You could achieve the same effect by making isLoaded a boolean[] of size 1, but that seems less elegant than going with AtomicBoolean to me.
But seriously, try using an old-school loop instead too and see which one you like better.
If you use parallel stream, you must use AtomicBoolean. Because boolean[1] may not be safe in parallel scenario.
The java.util.stream javadoc states that
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.
That said, if you want to do it anyway, the solution you have identified with an AtomicBoolean will do the trick just fine.
Variables used within anonymous inner classes and lambda expression have to be effectively final.
You can use AtomicReference for your case, here is a similar snippet from ConditionEvaluationListenerJava8Test
public void expectedMatchMessageForAssertionConditionsWhenUsingLambdasWithoutAlias() {
final AtomicReference<String> lastMatchMessage = new AtomicReference<>();
CountDown countDown = new CountDown(10);
with()
.conditionEvaluationListener(condition -> {
try {
countDown.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
lastMatchMessage.set(condition.getDescription());
})
.until(() -> assertEquals(5, (int) countDown.get()));
String expectedMatchMessage = String.format("%s reached its end value", CountDown.class.getName());
assertThat(lastMatchMessage.get(), allOf(startsWith("Condition defined as a lambda expression"), endsWith(expectedMatchMessage)));
}
Cheers !
If I right understand you will get isLoaded=false only in case if all off result lists will be empty (If result list is null you will get NPE in the next line so there is no any reason to do null check in this way). In this case your data list also will be empty and you don't need any boolean flags, just check if data.isEmpty() and return false if true.

Get all the conditions which resulted in rule execution

I want to get all the individual conditions which resulted in the execution of a rule.
For example, if I have the following rule:
package app1;
rule 'rule1'
when
MyObjectType1( booleanPredicate1() )
or
(
MyObjectType2( booleanPredicate2() )
and
MyObjectType3( booleanPredicate3() )
)
or
MyObjectType4( booleanPredicate4() )
then
System.out.println("In rule - " + drools.getRule().getName());
end
and booleanPredicate1(), booleanPredicate2() and booleanPredicate4() are true, then I want to get the following output:
booleanPredicate1() resulted in rule execution.
booleanPredicate4() resulted in rule execution.
What I've tried so far is inside the implementation of all such predicate methods, I've added a logging statement which gets executed only when that method is going to return true:
boolean booleanPredicate1()
{
boolean ret = false;
...
...
if (<business-logic-defined-predicate>)
{
ret = true;
}
if(ret)
{
addToLog("booleanPredicate1 became true.");
}
return ret;
}
but with this solution, I'll also get the output booleanPredicate2() resulted in rule execution. which is wrong.
Is there any way with which I can get the correct logging results?
Consult my paper on rule design patterns it has a section answering your question.
To summarize it here: you need rules for the individual truth values to register what is true for some fact or some combination of facts. The rule as you have it now will then combine the boolean values from the registry, and registry contains the answer to your problem.

make wait function do something on and on if it fails

I am very beginner with Selenium and Java to write tests.
I know that I can use the code below to try to click on a web element twice (or as many time as I want):
for(int i=0;i<2;i++){
try{
wait.until(wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//button[text()='bla bla ..']"))).click();
break;
}catch(Exception e){ }
}
but i was wondering if there is anything like passing a veriable to the wait function to make it do it ith times itself, something like:
wait.until(wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//button[text()='bla bla ..']"),2)).click();
For example in here 2 may mean that try to do it two times if it fails, do we have such a thing?
Take a look at FluentWait, I think this will cover your use case specifying appropriate timeout and polling interval.
https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html
If you can't find something in the set of ExpectedConditions that does what you are wanting you can always write your own.
The WebDriverWait.until method can be passed either a com.google.common.base.Function or com.google.common.base.Predicate. If you create your own Function implementation then it's good to note that any non-null value will end the wait condition. For Predicate the apply method simply needs to return true.
Armed with that I do believe there's very little you can't do with this API. The feature you're asking about probably does not exist out of the box, but you have full capability to create it.
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Predicate.html
Best of Luck.
Untested Snippet
final By locator = By.xpath("");
Predicate<WebDriver> loopTest = new Predicate<WebDriver>(){
#Override
public boolean apply(WebDriver t) {
int tryCount = 0;
WebElement element = null;
while (tryCount < 2) {
tryCount++;
try {
element = ExpectedConditions.visibilityOfElementLocated(locator).apply(t);
//If we get this far then the element resolved. Break loop.
break;
} catch (org.openqa.selenium.TimeoutException timeout) {
//FIXME LOG IT
}
}
return element != null;
}
};
WebDriverWait wait;
wait.until(loopTest);

How to use OR condition with TestNG assertions

Is there a way to do assertions with OR with TestNG?
This is what I am trying to find:
assertEquals(expected, value1 || value2); // Can be any number of values.
You could make a very simple wrapper around the TestNG code:
private void assertContains(Object actual, Object ... expected) {
assertTrue(Arrays.asList(expected).contains(actual));
}
I briefly looked through the TestNG source code and didn't see any methods similar to the method above, but I am not very familiar with the TestNG patterns.
I just did a workaround with boolean assertions:
if(condition1 || condition2){
Assert.assertTrue(true)
} else {
Assert.fail("Your Explanation here")
}

Custom hamcrest matcher that works with "not"?

I have some class (say, Entity).
I want to be able to
test that an instance of that is "valid", using some custom code to decide that
also test that an instance is not valid, ideally using the same code.
Using maven, surefire, JUnit 4.11 (and the hamcrest stuff shipped with it).
So I write a class something like this
class IsValidEntity extends TypeSafeMatcher<Entity>{
#Override public boolean matchesSafely(Entity e){
// and here I do a bunch of asserts...
assertNotNull(e.id);
// etc.
}
#Override
public void describeTo(Description description) {
description.appendText("is valid entity");
}
#Factory
public static <T> Matcher<Entity> validEntity() {
return new IsValidEntity();
}
}
OK, fine, I can then do
assertThat(entity, is(validEntity());
in a JUnit test, peachy.
But I can't do
assertThat(entity, not(validEntity());
because the validEntity fails with broken asserts, while for not I guess it should just return false.
Clearly I'm doing something backwards here but I'm not sure what's the most clever way of doing these custom matchers. Or maybe I shouldn't be using TypeSafeMatcher at all but doing something different?
Your matchesSafely method should be rewritten to avoid throwing assertion failures. Instead, just perform the checks manually and then return false if necessary.
Then, you can negate it in the manner you desire without consequence.
You should not be using assert methods in the matchesSafely. You should only be doing boolean logic to return either true or false. It is the responsibility of the calling code to throw the assert error and / or wrap in the not. Therefore you should be doing something like this:
public boolean matchesSafely(...){
boolean result = true;
result &= value1 == value2;
result &= entity.getVal2() == someOtherVal2;
return result;
}
While the other answers are more correct, another approach might be to catch your exceptions within the matcher and then return false while swallowing the exception and returning true otherwise.
This is not ideal.

Categories