NUnit CategoryName - selenium

I tried for the first time using TestCase as explained here.
I normally got the category name (for debug purpose) like this:
lstCategories = (System.Collections.IList)NUnit.Framework.TestContext.CurrentContext.Test.Properties["Category"];
and then found the category name like this:
(string)lstCategories[0]
But when I use TestCase I could not get it (it is empty).
Please help.

Did you setup your [Test] method as in the example which you provided? There is an example of how to pass data to the test method:
private static IEnumerable<TestCaseData> AddBrowserConfs()
{
yield return new TestCaseData("chrome", "72.0", "Windows 10");
yield return new TestCaseData("internet explorer", "11.0", "Windows 10");
yield return new TestCaseData("Safari", "11.0", "macOS High Sierra");
yield return new TestCaseData("MicrosoftEdge", "18.0", "Windows 10");
}
[Test, TestCaseSource("AddBrowserConfs")]
public void DuckDuckGo_TestCaseSource_Demo(String browser, String version, String os)
{
As you can see, values from AddBrowserConfs are passed as arguments in DuckDuckGo_TestCaseSource_Demo. Does this answer your question?

With test cases you are not getting Category name because its not set properly. You need to set it with each test cases as below:
[Test]
[TestCase(12, 4, Category = "MyCat")]
[TestCase(10, 6, Category = "MyCat")]
public void Test2(int a, int b)
{
Assert.AreEqual(a + b, 16);
var catName = TestContext.CurrentContext.Test.Properties.Get("Category").ToString();
Console.WriteLine(catName);
}
OR if you are using TestCaseSource, add Category name as below:
[Test]
[TestCaseSource(typeof(AddCases), Category = "MyCat")]
public void Test2(int a, int b)
{
Assert.AreEqual(a + b, 16);
}
public class AddCases : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new object[] { 8, 8 };
yield return new object[] { 10, 6 };
yield return new object[] { 12, 4 };
}
}
Hope this helps.

Related

What happens if no records exists when I use Room to query?

I use Room in my Android Studio App, the Code A will crash when no record exists to query
What happens if no records exists when I use Room to query with Code B ?
#Dao
interface RecordDao {
// Code A
#Query("SELECT * FROM record_table where id=:id")
fun getByID(id:Int): Flow<RecordEntity>
// Code B
#Query("SELECT * FROM record_table")
fun getAll(): Flow<List<RecordEntity>>
}
If you look at the code generated by room for the RecordDao_Impl class implementation of RecordDao, you'll notice multiple things:
The getById function code returns null when no matching records exist in the table, and since your 'Code A' function return type is not null, kotlin throws a NullPointerException for the first function.
The getAll function code returns a Flow object with an ArrayList, in case it found any records then it adds them to the list, otherwise it just emits the empty ArrayList to the Flow object, therefore, you'll always get a flow object with a list inside it regardless if room found matching records or not, so no exception is thrown.
You can understand this a bit more if you look at the code generated for the two functions here:
#Override
public Flow<RecordEntity> getByID(final int id) {
final String _sql = "SELECT * FROM record_table where id=?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
_statement.bindLong(_argIndex, id);
return CoroutinesRoom.createFlow(__db, false, new String[]{"record_table"}, new Callable<RecordEntity>() {
#Override
public RecordEntity call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final RecordEntity _result;
if (_cursor.moveToFirst()) {
final int _tmpId;
_tmpId = _cursor.getInt(_cursorIndexOfId);
_result = new RecordEntity(_tmpId);
} else {
_result = null;
}
return _result;
} finally {
_cursor.close();
}
}
#Override
protected void finalize() {
_statement.release();
}
});
}
#Override
public Flow<List<RecordEntity>> getAll() {
final String _sql = "SELECT * FROM record_table";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return CoroutinesRoom.createFlow(__db, false, new String[]{"record_table"}, new Callable<List<RecordEntity>>() {
#Override
public List<RecordEntity> call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final List<RecordEntity> _result = new ArrayList<RecordEntity>(_cursor.getCount());
while (_cursor.moveToNext()) {
final RecordEntity _item;
final int _tmpId;
_tmpId = _cursor.getInt(_cursorIndexOfId);
_item = new RecordEntity(_tmpId);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
}
}
#Override
protected void finalize() {
_statement.release();
}
});
}

How to generate data class from class instance

I've got some configuration values in a JSON file which I want to parse via gson to a data-class. I want to generate a new class, based on the created data-class where the values are final.
This all should happen during my CI-Pipeline and the generated class should then be used when my application is running.
Simple example to clarify:
I've got this data class
data class MyDataClass(val name:String, val age:Int)
and via parsing (gson) a instance like this is created
MyDataClass("john", 42)
Is there a way to create a (data) class based on the new instance of MyDataClass so anything like this will be created?
class MyDataClassFinal{
val name = "john"
val age = 42
}
Use .copy() and modify only the parameters you need to. For example:
val joe = MyDataClass(“Joe”, 42)
val mary = joe.copy(name = “Mary”) // age is 42
I've got some configuration values in a json file wich I want to parse via gson to a data-class. I want to generate a new class, based on the created data-class where the values are final.
There is nothing for you to do here. The data class, as you've described it, is final. It is not open so the class is final and the fields are vals and only set via constructor, so they can't be changed, so they too are final.
You can see the Java equivalent of the class by going to doing a search for "Actions", looking for Kotlin Bytecode, then hit Decompile to see the Java source. It looks like this:
#Metadata(
mv = {1, 1, 18},
bv = {1, 0, 3},
k = 1,
d1 = {"\u0000 \n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\u000e\n\u0000\n\u0002\u0010\b\n\u0002\b\t\n\u0002\u0010\u000b\n\u0002\b\u0004\b\u0086\b\u0018\u00002\u00020\u0001B\u0015\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0004\u001a\u00020\u0005¢\u0006\u0002\u0010\u0006J\t\u0010\u000b\u001a\u00020\u0003HÆ\u0003J\t\u0010\f\u001a\u00020\u0005HÆ\u0003J\u001d\u0010\r\u001a\u00020\u00002\b\b\u0002\u0010\u0002\u001a\u00020\u00032\b\b\u0002\u0010\u0004\u001a\u00020\u0005HÆ\u0001J\u0013\u0010\u000e\u001a\u00020\u000f2\b\u0010\u0010\u001a\u0004\u0018\u00010\u0001HÖ\u0003J\t\u0010\u0011\u001a\u00020\u0005HÖ\u0001J\t\u0010\u0012\u001a\u00020\u0003HÖ\u0001R\u0011\u0010\u0004\u001a\u00020\u0005¢\u0006\b\n\u0000\u001a\u0004\b\u0007\u0010\bR\u0011\u0010\u0002\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\t\u0010\n¨\u0006\u0013"},
d2 = {"Lcore/lib/extensions/MyDataClass;", "", "name", "", "age", "", "(Ljava/lang/String;I)V", "getAge", "()I", "getName", "()Ljava/lang/String;", "component1", "component2", "copy", "equals", "", "other", "hashCode", "toString", "treking-android.dominicore-android"}
)
public final class MyDataClass {
#NotNull
private final String name;
private final int age;
#NotNull
public final String getName() {
return this.name;
}
public final int getAge() {
return this.age;
}
public MyDataClass(#NotNull String name, int age) {
Intrinsics.checkParameterIsNotNull(name, "name");
super();
this.name = name;
this.age = age;
}
#NotNull
public final String component1() {
return this.name;
}
public final int component2() {
return this.age;
}
#NotNull
public final MyDataClass copy(#NotNull String name, int age) {
Intrinsics.checkParameterIsNotNull(name, "name");
return new MyDataClass(name, age);
}
// $FF: synthetic method
public static MyDataClass copy$default(MyDataClass var0, String var1, int var2, int var3, Object var4) {
if ((var3 & 1) != 0) {
var1 = var0.name;
}
if ((var3 & 2) != 0) {
var2 = var0.age;
}
return var0.copy(var1, var2);
}
#NotNull
public String toString() {
return "MyDataClass(name=" + this.name + ", age=" + this.age + ")";
}
public int hashCode() {
String var10000 = this.name;
return (var10000 != null ? var10000.hashCode() : 0) * 31 + this.age;
}
public boolean equals(#Nullable Object var1) {
if (this != var1) {
if (var1 instanceof MyDataClass) {
MyDataClass var2 = (MyDataClass)var1;
if (Intrinsics.areEqual(this.name, var2.name) && this.age == var2.age) {
return true;
}
}
return false;
} else {
return true;
}
}
}
As you can see, the class, it's fields, and their accessors are all final.

ITestResult.getTestName() in TestNG listener returns testname = null despite of setting name #Test(testName="Browser") on test method

How to get the custom testName of the test in the listener?
TestDemo.java
#Test(testName = "Browser", description = "This is browser test", priority = 1)
public void launchTest() throws IOException {
System.out.println("I am in the test");
}
Listener class
ListenerDemo.java
//some code
public void onTestStart(ITestResult result) {
System.out.println(result.getMethod().getDescription()); //return dexcription as expected
System.out.println(result.getMethod().getPriority()); //return priority as expected
//Already Tried options but none of them worked
System.out.println("Name "+result.getName()); //returns Name = launchTest
System.out.println("Name "+result.getTestName()); //returns Name = null
System.out.println("Name "+ result.getMethod().getMethodName()); //returns Name = launchTest
//I am expecting one of the statement should return Name="Browser"
}
Already looked at ITestResult getTestName() returns null despite of set test name by #Test(testName = "sth") but this doesn't provide any useful answer
I am using TestNG version 7.1.0.
After some research, I found out this and it worked for me
public void onTestStart(ITestResult result) {
Method method = result.getMethod().getConstructorOrMethod().getMethod();
Test test = method.getAnnotation(Test.class);
String testname = test.testName();
}
Try this, it worked for me...
public void onTestStart(ITestResult result) {
Method method = result.getMethod().getConstructorOrMethod().getMethod();
Test test = method.getAnnotation(Test.class);
String testname = test.testName();
System.out.println(testname+" started");
}

Mono.CSharp: how do I inject a value/entity *into* a script?

Just came across the latest build of Mono.CSharp and love the promise it offers.
Was able to get the following all worked out:
namespace XAct.Spikes.Duo
{
class Program
{
static void Main(string[] args)
{
CompilerSettings compilerSettings = new CompilerSettings();
compilerSettings.LoadDefaultReferences = true;
Report report = new Report(new Mono.CSharp.ConsoleReportPrinter());
Mono.CSharp.Evaluator e;
e= new Evaluator(compilerSettings, report);
//IMPORTANT:This has to be put before you include references to any assemblies
//our you;ll get a stream of errors:
e.Run("using System;");
//IMPORTANT:You have to reference the assemblies your code references...
//...including this one:
e.Run("using XAct.Spikes.Duo;");
//Go crazy -- although that takes time:
//foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
//{
// e.ReferenceAssembly(assembly);
//}
//More appropriate in most cases:
e.ReferenceAssembly((typeof(A).Assembly));
//Exception due to no semicolon
//e.Run("var a = 1+3");
//Doesn't set anything:
//e.Run("a = 1+3;");
//Works:
//e.ReferenceAssembly(typeof(A).Assembly);
e.Run("var a = 1+3;");
e.Run("A x = new A{Name=\"Joe\"};");
var a = e.Evaluate("a;");
var x = e.Evaluate("x;");
//Not extremely useful:
string check = e.GetVars();
//Note that you have to type it:
Console.WriteLine(((A) x).Name);
e = new Evaluator(compilerSettings, report);
var b = e.Evaluate("a;");
}
}
public class A
{
public string Name { get; set; }
}
}
And that was fun...can create a variable in the script's scope, and export the value.
There's just one last thing to figure out... how can I get a value in (eg, a domain entity that I want to apply a Rule script on), without using a static (am thinking of using this in a web app)?
I've seen the use compiled delegates -- but that was for the previous version of Mono.CSharp, and it doesn't seem to work any longer.
Anybody have a suggestion on how to do this with the current version?
Thanks very much.
References:
* Injecting a variable into the Mono.CSharp.Evaluator (runtime compiling a LINQ query from string)
* http://naveensrinivasan.com/tag/mono/
I know it's almost 9 years later, but I think I found a viable solution to inject local variables. It is using a static variable but can still be used by multiple evaluators without collision.
You can use a static Dictionary<string, object> which holds the reference to be injected. Let's say we are doing all this from within our class CsharpConsole:
public class CsharpConsole {
public static Dictionary<string, object> InjectionRepository {get; set; } = new Dictionary<string, object>();
}
The idea is to temporarily place the value in there with a GUID as key so there won't be any conflict between multiple evaluator instances. To inject do this:
public void InjectLocal(string name, object value, string type=null) {
var id = Guid.NewGuid().ToString();
InjectionRepository[id] = value;
type = type ?? value.GetType().FullName;
// note for generic or nested types value.GetType().FullName won't return a compilable type string, so you have to set the type parameter manually
var success = _evaluator.Run($"var {name} = ({type})MyNamespace.CsharpConsole.InjectionRepository[\"{id}\"];");
// clean it up to avoid memory leak
InjectionRepository.Remove(id);
}
Also for accessing local variables there is a workaround using Reflection so you can have a nice [] accessor with get and set:
public object this[string variable]
{
get
{
FieldInfo fieldInfo = typeof(Evaluator).GetField("fields", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
var fields = fieldInfo.GetValue(_evaluator) as Dictionary<string, Tuple<FieldSpec, FieldInfo>>;
if (fields != null)
{
if (fields.TryGetValue(variable, out var tuple) && tuple != null)
{
var value = tuple.Item2.GetValue(_evaluator);
return value;
}
}
}
return null;
}
set
{
InjectLocal(variable, value);
}
}
Using this trick, you can even inject delegates and functions that your evaluated code can call from within the script. For instance, I inject a print function which my code can call to ouput something to the gui console window:
public delegate void PrintFunc(params object[] o);
public void puts(params object[] o)
{
// call the OnPrint event to redirect the output to gui console
if (OnPrint!=null)
OnPrint(string.Join("", o.Select(x => (x ?? "null").ToString() + "\n").ToArray()));
}
This puts function can now be easily injected like this:
InjectLocal("puts", (PrintFunc)puts, "CsInterpreter2.PrintFunc");
And just be called from within your scripts:
puts(new object[] { "hello", "world!" });
Note, there is also a native function print but it directly writes to STDOUT and redirecting individual output from multiple console windows is not possible.

Rhino moq Property.value constraint

My following straight forward test doesn't pass (Though I feel it should). Either I am missing something or is not clear of Property.value constraint. please help me in understanding concept of property.value constraint.
public interface ISomeInterface
{
void SomeMethod(string x, string y);
}
public class SomeClassTest
{
[Test]
public void SomeMethodTest()
{
MockRepository mocks = new MockRepository();
ISomeInterface mockservice = mocks.StrictMock<ISomeInterface>();
using (mocks.Record())
{
mockservice.SomeMethod("xValue", "yValue");
LastCall.Constraints(Property.Value("x", "xValue"),
Property.Value("y", "yValue"));
}
mockservice.SomeMethod("xValue", "yValue");
mocks.Verify(mockservice);
}
}
Exception raised:
Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.SomeMethod("xValue", "yValue"); Expected #0, Actual #1.
ISomeInterface.SomeMethod(property 'x' equal to xValue, property 'y' equal to yValue); Expected #1, Actual #0.
I would recommend you the following syntax (AAA syntax):
// arrange
var mockservice = MockRepository.GenerateMock<ISomeInterface>();
// act
mockservice.SomeMethod("xValue", "yValue");
// assert
mockservice.AssertWasCalled(
x => x.SomeMethod("xValue", "yValue")
);
This sample class illustrates the options for asserting methods were called with appropriate properties:
public class UsesThing
{
private IMyThing _thing;
public UsesThing(IMyThing thing)
{
_thing = thing;
}
public void DoTheThing(int myparm)
{
_thing.DoWork(myparm, Helper.GetParmString(myparm));
}
public void DoAnotherThing(int myparm)
{
AnotherThing thing2 = new AnotherThing();
thing2.MyProperty = myparm + 2;
_thing.DoMoreWork(thing2)
}
}
Using simple values for assertions may work for methods like the DoTheThing method which uses value types:
[Test]
public void TestDoTheThing()
{
IMyThing thing = MockRepository.GenerateMock<IMyThing>();
UsesThing user = new UsesThing(thing);
user.DoTheThing(1);
thing.AssertWasCalled(t => t.DoWork(1, "one");
}
However, if you need to create an object in your method and pass it as a parameter like in the DoAnotherThing method, this approach will not work since you will not have a reference to the object. You have to check the property values of the unknown object, like this:
[Test]
public void TestDoAnotherThing()
{
IMyThing thing = MockRepository.GenerateMock<IMyThing>();
UsesThing user = new UsesThing(thing);
user.DoAnotherThing(1);
thing.AssertWasCalled(t => t.DoMoreWork(null), t => t.IgnoreArguments().Constraints(Property.Value("MyProperty", 3))));
}
The new Rhino syntax would look like the following, but I am crashing VS 2008 when I use it:
thing.AssertWasCalled(t => t.DoMoreWork(Arg<AnotherThing>.Matches(Property.Value("MyProperty", 3))));