Test android app writen in java with kotlin test - java

I'm trying to add UI-tests to my android app, decided to work with kotlin and not with Java.
I have added a new kotlin file to my "androidTest" folder
I followed this tutrial
When I'm trying to run the test i'm getting:
Empty test suite.
just to emphasize - I'm writing to test in kotlin but the app is written in Java, is that even ok? or it can't even work?
My code:
package maakesher.com.black.packagename
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.rule.ActivityTestRule
import androidx.test.filters.LargeTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
#LargeTest
class ChangeTextBehaviorTest {
private lateinit var stringToBetyped: String
#get:Rule
var activityRule: ActivityTestRule<MainMenuActivity> = ActivityTestRule(MainMenuActivity::class.java)
#Before
fun initValidString() {
// Specify a valid string.
stringToBetyped = "Espresso"
}
#Test
fun testSomeStuff() {
// Type text and then press the button.
onView(withId(R.id.start_button))
.perform(click())
}
}
Thanks.

After a long night found the answer:
Needed to add this to mu Gradle file
sourceSets {
test.java.srcDirs += 'src/test/kotlin/'
androidTest.java.srcDirs += 'src/androidTest/kotlin/'
}

Related

Why is it that the texture isn´t loading? Minecraft 15.2 Forge 31.2

I am trying to apply a texture to an item created with forge for Minecraft but for some reason it wouldn´t load. I am new to this so I cant recognize where the problem is, so I will upload multiple lines of code.
This code is from itemInit.Java:
package com.example.examplemod.init;
import com.example.examplemod.ExampleMod;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.ObjectHolder;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
#Mod.EventBusSubscriber(modid = ExampleMod.MOD_ID, bus = Bus.MOD)
#ObjectHolder(ExampleMod.MOD_ID)
public class itemInit {
public static Item example_item = null;
#SubscribeEvent
public static void registerItems(final RegistryEvent.Register<Item> event) {
event.getRegistry().register(new Item(new Item.Properties().group(ItemGroup.MISC)).setRegistryName("example_item"));
}
}
This is the example_item.json:
{
"parent":"items/generated",
"textures":{
"layer0":"examplemod:items/example_item"
}
}
en_us.json:
{
"item.examplemod.example_item":"Super Seed"
}
And here is a picture of the project hierarchy:Project hierarchy
In your example_mod.json file, line 2, change it to
"parent": "item/generated",
Inside the directory assets\examplemod\models, you have two folders named blocks and items. Change their names to 'block' and 'item' without the quotation marks. If you encounter any other problem, post your error log using pastebin or some other site. Also, create a github repo for your project and then post the link here :)
Also, I recommend using DeferredRegister class and RegistryObjects to register your custom items.
Syntax:
public static final DeferredRegister<Item> NAME = new DeferredRegister<>(ForgeRegistries.ITEMS, "Your Mod ID");
public static final RegistryObject<Item> Example_item = NAME.register("Registry_Name", () -> new Item(new Item.Properties()));

How to Run Java Code from Gradle at Build Time

I'm using jsonschema-generator to generate a JSON schema file based on my POJOs. Currently I'm doing it via a test that is run during the gradle build step. This works fine but it doesn't feel right as really what I'm doing is not testing anything.
I've also found this answer which details how to run it on gradle run but this is not ideal either as it will pointlessly execute this every time the application comes up but not when I build.
Therefore, is there a way to tell gradle (in build.gradle) to run a piece of Java code at build time?
For completeness, here the code I'm looking to run:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.mypackage.MyClass;
import org.junit.jupiter.api.Test;
import java.io.PrintWriter;
import java.util.Map;
#SuppressWarnings({"FieldCanBeLocal", "rawtypes"})
public class JsonSchemaGenerator {
private final String SCHEMA_FOLDER = "schemas/";
private final Map<Class, String> schemaToGenerate = Map.of(
MyClass.class, "my-class.schema"
);
#Test
public void generateJsonSchema() throws Exception {
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.DEFINITIONS_FOR_ALL_OBJECTS).build();
SchemaGenerator generator = new SchemaGenerator(config);
for (var entry : schemaToGenerate.entrySet()) {
JsonNode jsonSchema = generator.generateSchema(entry.getKey());
PrintWriter out = new PrintWriter(SCHEMA_FOLDER + entry.getValue());
out.println(jsonSchema.toPrettyString());
out.close();
}
}
}
The JavaExec Plugin seems to meet your requirements.
This allows you to run a main() method and thereby any Java Code you want – including whatever JSON Schema generation you like.
This other answer also describes pretty much what you want to do.
Adapted from the linked documentation:
apply plugin: 'java'
task generateJsonSchema(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'package.Main'
// arguments to pass to the application
args 'appArg1'
}
As per Jorn's comment below:
You can depend the build task on your custom task: build.dependsOn generateJsonSchema if your custom task is defined as task generateJsonSchema(type: JavaExec) { ... }

Nashorn java.lang.NoClassDefFoundError: jdk/nashorn/api/scripting/JSObject

I am migrating my Eclipse RCP to use JDK 8 and I heavily use the JS ScriptEngine. Now that Nashorn is introduced I had to add the following line to get the importClass and importPackage functions to work:
load("nashorn:mozilla_compat.js");
After doing so, I got java.lang.NoClassDefFoundError: jdk/nashorn/api/scripting/JSObject.
I am using Nashorn inside an Eclipse RCP. The problem occurs when I call a Java function from the Javascript and try to use the parameter sent. The parameter I want to send is a Javascript function that I would like to execute call on later in the code.
I have the following code:
TestNashorn.java
package com.test.nashorn;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.Invocable;
import jdk.nashorn.api.scripting.JSObject;
public class TestNashorn {
public static void main(String[] args) {
ScriptEngine engine = (new ScriptEngineManager()).getEngineByName("js");
try {
engine.eval(new FileReader("C:/Users/user/workspace_nashorn/TestNashorn/src/com/test/nashorn/test.js"));
Object o = ((Invocable)engine).invokeFunction("generate");
} catch (ScriptException | FileNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
public static int test(JSObject o1) {
System.out.println(o1.getClass().toString());
JSObject som = ((JSObject)o1);
return 1;
}
}
test.js
load("nashorn:mozilla_compat.js");
importClass(com.test.nashorn.TestNashorn);
function generate()
{
function asd(variablex) { print('Hello, ' + variablex); }
var result = TestNashorn.test(asd);
}
The problem occurs in line JSObject som = ((JSObject)o1);, although I can successfully import jdk.nashorn.api.scripting.JSObject;.
The exception message exactly says:
jdk.nashorn.api.scripting.JSObject cannot be found by com.test.nashorn_1.0.0.qualifier
So.. I got to fix my issue and was able to use JSObject in my code. What I have done was the following:
Added -Dorg.osgi.framework.bundle.parent=ext to myproduct.product file
This added it to the .ini file in my product build which revealed the classes found in Nashorn APIs.

Javafx by kotlin went wrong when I export it to runnable jar

I try to write javafx application using kotlin. After I export it to runnable jar,I double click jar file but it doesn't work. But everything ok if I use Java.
For example: Create a new javafx project by IDEA 2017.2.5.Select File-Project Structure,then click JavaFX tab,Native bundle choose all.Then apply setting.
Then choose Build-Build Artifact-Build.
I can run it.Everything OK.
But when I use kotlin and do same thing as java.
Everything ok when I run it in IDEA.
code:
package sample
import javafx.application.Application
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
class Main : Application() {
#Throws(Exception::class)
override fun start(primaryStage: Stage) {
val root = FXMLLoader.load<Parent>(javaClass.getResource("sample.fxml"))
primaryStage.title = "Hello World"
primaryStage.scene = Scene(root, 300.0, 275.0)
primaryStage.show()
}
companion object {
#JvmStatic
fun main(args: Array<String>) {
Application.launch(Main::class.java)
}
}
}
I double click it but nothing happend.What's wrong???

SdkManager class is not available in latest android SDK

Downloaded latest android Studio (android-studio-bundle-162.3871768-windows).
We were using com.android.sdklib.SdkManager class in our software but in latest Android Studio I'm not able to find the above mentioned class in any jar present inside the tools\lib folder.
Can anyone suggest what is the better alternative for this?
if you want to get a list of all the targets installed for knowledge, then you can just simply run the SDK manager. But since you want to call the getTargets() method, it means you need it for other purposes. check up the documentation on the android studio web page to find out if it the class you are searching for exists and the location of its jar file.
We can find the soure code of all the android classes in the below link.
https://javalibs.com/artifact/com.android.tools/sdklib?className=com.android.sdklib.tool.SdkManagerCli&source
SdkManagerCli class have equivalent method listPackages()which will list the packages.
We need to import sdklib-25.3.2.jar, repository-25.3.2.jar and common-25.3.2.jar to project.
Below is the working code for listing packages:-
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.TreeSet;
import com.android.repository.Revision;
import com.android.repository.api.ConsoleProgressIndicator;
import com.android.repository.api.LocalPackage;
import com.android.repository.api.ProgressIndicator;
import com.android.repository.api.RepoManager;
import com.android.repository.impl.meta.RepositoryPackages;
import com.android.sdklib.repository.AndroidSdkHandler;
public class AndroidTesting {
public static void main(String[] args) {
listPackages();
}
private static void listPackages() {
AndroidSdkHandler mHandler = AndroidSdkHandler.getInstance(new
File("filePath")); //for eg:-sdk/platforms for API
ProgressIndicator progress = new ConsoleProgressIndicator();
RepoManager mRepoManager = mHandler.getSdkManager(progress);
mRepoManager.loadSynchronously(cacheExpirationMs, progress,
downloader, settings)(0, progress, null, null);
RepositoryPackages packages = mRepoManager.getPackages();
Collection<LocalPackage> locals = new TreeSet<LocalPackage>();
Collection<LocalPackage> localObsoletes = new
TreeSet<LocalPackage>();
for (LocalPackage local : packages.getLocalPackages().values()) {
if (local.obsolete()) {
localObsoletes.add(local);
} else {
locals.add(local);
}
Revision version = local.getVersion();
System.out.println(local.getDisplayName() + " "
+ local.getVersion() );
}
}
}

Categories

Resources