Current InvocationCount in TestNG - eclipse

I have a method to be tested using TestNG and I have marked it with below annotations:
#Test(invocationCount=10, threadPoolSize=5)
Now, in my test method I would like to get the current invocationCount that is being executed. Is that possible? If yes, then I would be glad to know how.
More proper example:
#Test(invocationCount=10, threadPoolSize=5)
public void testMe() {
System.out.println("Executing count: "+INVOCATIONCOUNT); //INVOCATIONCOUNT is what I am looking for
}
For reference, I am using TestNG plugin in Eclipse.

You can use TestNG dependency injection feature by adding ITestContext parameter in your test method. Please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection.
From the ITestContext parameter, you can call its getAllTestMethods() which returns array of ITestNGMethod. It should returns array of only one element, which refers to the current/actual test method. Finally, you can call getCurrentInvocationCount() of ITestNGMethod.
Your test code should be more-less like the following sample,
#Test(invocationCount=10, threadPoolSize=5)
public void testMe(ITestContext testContext) {
int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();
System.out.println("Executing count: " + currentCount);
}

You can get the current invocation count as mentioned below
public class getCurrentInvocationCount {
int count;
#BeforeClass
public void initialize() {
count = 0;
}
#Test(invocationCount = 10)
public void testMe() {
count++;
System.out.println("Current Invocation count "+count)
}
}
I know this is a some kind of stupid way. However it will server your purpose. You can refer testNG source class to get actual current invocationCount

You can use something like this:
public class getCurrentInvocationCount {
AtomicInteger i = new AtomicInteger(0);
#Test(invocationCount = 10, threadPoolSize=5)
public void testMe() {
int count= i.addAndGet(1);
System.out.println("Current Invocation count "+count)
}
}

You can get by calling getCurrentInvocationCount() method of ITestNGMethod

Try to put 2 parameters in #Test method:
java.lang.reflect.Method
Use .getName() to get current method name.
ITestContext
Use .getAllTestMethods() to get all test methods. Then use forEach to extract them by ITestNGMethod and compare with .getName() in point 1.
Finally, use .getCurrentInvocationCount() to achieve this.
#Test(invocationCount=10)
public void testMe(ITestContext context, Method method) {
int invCountNumber = 0;
for(ITestNGMethod iTestMethod: context.getAllTestMethods()) {
if(iTestMethod.getMethodName().equals(method.getName())){
invCountNumber = iTestMethod.getCurrentInvocationCount();
break;
}
}
System.out.println(invCountNumber);
}
Following import:
import java.lang.reflect.Method;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;

When you use invocationCount the test is run like for loop.
I found this to be the easiest way to get the count of test executions.
int count;
#Test(invocationCount = 3)
public void yourTest() {
count++;
System.out.println("test executed count is: " + count)
}

Related

run method and store it one variable before each test in Nunit

I need to run a method before each test Like how before method works in TestNg.
What I am expecting is I need to take the Testname and find the relevant test data and store it variable. Currently I have included that step in Test. But it would be good to have to reduce a line of code in each test.
is it possible in Nunit?
Setup attribute is used to provide a common set of functions that are performed just before each test method is called. You can also get the Method name from TestContext.CurrentContext.Test.MethodName. There are also other properties on Test like Arguments or FullName depending on what you need.
[SetUp]
public void Setup()
{
var testName = TestContext.CurrentContext.Test.MethodName;
TestContext.WriteLine($"SetUp for {testName}");
}
Alternately, you can also use TestCaseData class which provides extended test case information for a parameterized test.
public class DemoClass {
[TestCaseSource(typeof(MyDataClass), nameof(MyDataClass.DivideTestCases))]
public int DivideTest(int n, int d)
{
return n / d;
}
[TestCaseSource(typeof(MyDataClass), nameof(MyDataClass.AddTestCases))]
public int AddTest(int a, int b)
{
return a + b;
}
}
public class MyDataClass
{
public static IEnumerable DivideTestCases
{
get
{
yield return new TestCaseData(12, 3).Returns(4);
yield return new TestCaseData(12, 2).Returns(6);
yield return new TestCaseData(12, 4).Returns(3);
}
}
public static IEnumerable AddTestCases
{
get
{
yield return new TestCaseData(10, 15).Returns(25);
yield return new TestCaseData(12, 10).Returns(22);
yield return new TestCaseData(14, 5).Returns(19);
}
}
}

Find direct & indirect method usages if method is overriden in base class

please, help me to figure out how to write the query :)
The code is:
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var man = new Man("Joe");
Console.WriteLine(man.ToString());
}
}
public class SuperMan
{
public SuperMan(string name)
{
this.name = name;
}
public override string ToString()
{
return name;
}
string name;
}
public class Man : SuperMan
{
public Man(string name) : base(name)
{
}
}
}
I want to find all direct and indirect dependencies (methods) to Man.ToString(). There is only one call in Main() method.
The query I'm trying is:
from m in Methods
let depth0 = m.DepthOfIsUsing("ConsoleApplication1.SuperMan.ToString()")
where depth0 >= 0 orderby depth0
select new { m, depth0 }.
but it doesn't find dependent Program.Main() method....
How to modify query so that it finds usages for such kind of methods?
First let's look at direct callers. We want to list all methods that calls SuperMan.ToString() or any ToString() methods overriden by SuperMan.ToString(). It can looks like:
let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
from m in Application.Methods.UsingAny(baseMethods)
where m.IsUsing("ConsoleApplication1.Man") // This filter can be added
select new { m, m.NbLinesOfCode }
Notice we put a filter clause, because in the real world pretty much every method calls object.ToString() (this is a particular case).
Now to handle indirect calls this is more tricky. We need to call the magic FillIterative() extension methods on generic sequences.
let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
let recursiveCallers = baseMethods.FillIterative(methods => methods.SelectMany(m => m.MethodsCallingMe))
from pair in recursiveCallers
let method = pair.CodeElement
let depth = pair.Value
where method.IsUsing("ConsoleApplication1.Man") // Still same filter
select new { method , depth }
Et voilà!

AspectJ applying Around advice on methods that return void

given a block of Advice like below:
#Around("execution(* com.myproject..*(..))")
public Object log(ProceedingJoinPoint pjp) throws Throwable{
....
Object result = pjp.proceed();
......
return result;
}
I just want to know if I have a method that returns void, will this Advice get applied, and will that result in some kind of error?
Example:
package com.myproject.mypackage;
public Class MyClass {
public void run() {
// Will this method run properly as a result of 'pjp.proceed()' above?
}
}
Tried experimenting by running a few stub methods myself, I found that the Advice will get applied, and there will be no error other than those generated by the joinpoint itself.

Override TestNG's getTestName method

I execute a TestNG test using a dataProvider.
So I set the testName via #BeforeMethod and I override getTestName().
This works so far, but it seems TestNG is calling the test's getTestName in the beginning
before it starts. This happens when an exception was thrown during configuration, so the #BeforeMethod is not executed and therefore my test name is null.
Is there anyway to call the original method, the one that would have been called if I would not have overwritten it :D since I implement an interface an do not extend from another class I cannot use super.getTestName().
Any way to solve this may be?
#Test(groups = {TestGroups.READY}, description = "check help on each tab")
public class HelpTest extends TestControl implements ITest {
// overriding to return my individual testname, but is null at the beginning
#Override
public String getTestName() {
return TestControl.getCurrentTestName();
}
#DataProvider(name = "tabs")
public Iterator<Object[]> tabs() {
Set<Object[]> list = new LinkedHashSet<Object[]>();
for (Tab tab : Tab.values()) {
list.add(new Object[]{tab});
}
return list.iterator();
}
// before the test below starts, i set my individual testname
#BeforeMethod
public void setTestName(Method method, Object[] testData) {
TestControl.setCurrentTestName(method.getName() + "_" + StringUtils.capitalize(testData[0].toString().toLowerCase()));
}
// executing the test with the given data provider
#Test(dataProvider = "tabs")
public void testHelpSites(Tab tab) throws Exception {
TestActions.goTab(tab).callHelp(tab).checkHelp();
}
}
I guess I figured it out, I also use a TestReporter via AbstractWebDriverEventListener and ITestListener and on its onTestStart(ITestResult result) it's calling the test's name and that's the source of the call before the #BeforeMethod call.
I solved it by checking if result.getName() is null, which calls the test's getTestName() if it implements ITest and if it's null I use the original name from result.getMethod.getMethodName(). Not pretty, but rare :D
I could solve this problem using ITestNGMethod testng class.
ITestNGMethod method = result.getMethod(); // result is ITestResult Object
method.getMethodName(); // This will return method name.
My complete method here:
#Override
public void onTestSuccess(ITestResult result) {
ITestNGMethod method = result.getMethod();
String message = "Test Execution is Successful:"+method.getMethodName();
}
Hope this helps

How to call java method from javascript method that located within another jsni method

public class A{
private void javaMethod(int a,int b){}
private native void init()/*-{
function OnMouseMove(e) {
//blow calling doesn't work
this.#p::javaMethod(Ljava/...teger;Ljava.../Integer;)(intVal,intVal);
}
}-*/;
}
As described above,how to make that invoking work?
Answered on the Google Group: https://groups.google.com/d/msg/google-web-toolkit/qE2-L4u_t4s/YqjOu-bUfsAJ
Copied here for reference and convenience:
First, int is not java.lang.Integer, so your method signature in JSNI is wrong; it should read javaMethod(II).
(I suppose the #p:: while javaMethod is defined in class A is over-simplification in your question, but is OK in your code)
You'll also probably have a problem with this, that might not be what you think it is. A common pattern is to assign the current object (this, at the time) to a variable that you'll reference from your closure:
var that = this;
…
function OnMouseMove(e) {
that.#p.A::javaMethod(II)(intVal, intVal);
}
You're doing two things wrong:
You're not defining the class name after #p, (assuming #p is actually just a shortened version of the real package's name);
You're attempting to pass java.lang.Integer in place of int. You should be saying (II) as the types, as described here.
Your code should look more like this:
package com.my.package;
public class ClassA {
private static void javaMethod(int a, int b) { ... }
public static native void init() /*-{
$wnd.javaMethod = function(a, b) {
return #com.my.package.ClassA::javaMethod(II)(a,b);
}
function OnMouseMove(e) {
$wnd.javaMethod(a,b);
}
}-*/;
}