Not able to use some Junit classes properly - java

I want to use ErrorCollector class in jUnit but not able to import its required class.
I want to import org.junit.rule.* but instead of that i get option for importing import sun.org.mozilla.javascript.internal.ast.ErrorCollector. I do not understand what is happening. I do not get any option for importing Rule class, I tried to type import org.junit.rule but its not imported successfully.
Please help or explain me what is going on?
Thanks.
package testcases;
import junit.framework.Assert;
import org.junit.Test;
//import sun.org.mozilla.javascript.internal.ast.ErrorCollector;
public class understandingAssertion {
#Rule
public ErrorCollector er = new ErrorCollector();
#Test
public void countFriendTest() {
int actual_fr = 100; //Selenium
int expected_Fr =10;
/*
if (actual_fr == expected_Fr) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
*/
System.out.println("A");
try
{
Assert.assertEquals(expected_Fr, actual_fr);
}
catch(Throwable e)
{
System.out.println("Error encountered");
}
}
}

Your IDE will probably only give you the option to import classes that exist on your classpath.
Add the jar to your classpath and you'll be able to import the class without error.

Related

Cant figure out why my Object repository isnt working - xpath is read as null

i am rather new to coding in general and Have gotten most of my code from my instructor who is on vacation at the moment
The problem i am having is i made my OR.properties and OR_Propertiesloader class
Inside the OR_Propertiesloader class i am able to print out the xpath
But when i put it into a test script it read the value as NULL
Here is my code so far
package com.reuseables;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
public class OR_PropertiesLoader {
private static Properties OR_P_Obj;
private static String userNameBox;
public static String userNameBoxEle(){
return userNameBox;
}
public static void load_OR_Properties() throws FileNotFoundException {
try {
OR_P_Obj = new Properties();
OR_P_Obj.load(
new FileInputStream(
new File(
System.getProperty("user.dir") +
"/src/test/resources/ObjectRepository/OR.properties")));
}catch (Exception e){
System.out.println("Unable to read property file. Pls check the location of the file");
}
}
public static String getProperty(String propertyName) {
return OR_P_Obj.getProperty(propertyName);
}
public static void initialize_OR_Configurations() throws FileNotFoundException {
load_OR_Properties();
userNameBox = getProperty("userNameBox");
}
public static void main(String[] args) throws FileNotFoundException {
OR_PropertiesLoader.initialize_OR_Configurations();
System.out.println(OR_PropertiesLoader.userNameBoxEle());
}
}
The line im trying to use in my properties file is
userNameBox =//input[#id='txtUsername']
And this is the part of the test script im trying to throw the xpath into
package com.login.tests;
import com.reuseables.BaseTest;
import com.reuseables.ConfigPropertiesLoader;
import com.reuseables.OR_PropertiesLoader;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test;
public class personalDetailsValidationScenario extends BaseTest {
#Test
public void ValidatePositivePersonalDetailsScenario () throws InterruptedException {
// Go to URL
driver.get(ConfigPropertiesLoader.getApplicationURL());
//Enter Username
driver.findElement(By.xpath(OR_PropertiesLoader.userNameBoxEle()));
driver.findElement(By.xpath(OR_PropertiesLoader.userNameBoxEle())).clear();
driver.findElement(By.xpath(OR_PropertiesLoader.userNameBoxEle())).sendKeys(Username);
...
I previously tried to throw a " System.out.println(OR_PropertiesLoader.userNameBoxEle());" but it also gave me a null before failing the test
If anybody is able to lend me a hand with this is would greatly appreciate it!
#pcalkins Oh my god, thank you! the god damn config was not loading
Im pretty sure i didnt do the fix exactly the way you meant it, as i said im seemingly not fully understanding the way java works sometimes as i mentioned im pretty new at coding
But basically the change i made was to the test script itself
package com.login.tests;
import com.reuseables.BaseTest;
import com.reuseables.ConfigPropertiesLoader;
import com.reuseables.OR_PropertiesLoader;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.FileNotFoundException;
public class personalDetailsValidationScenario extends BaseTest {
#Test
public void ValidatePositivePersonalDetailsScenario() throws InterruptedException, FileNotFoundException {
OR_PropertiesLoader.initialize_OR_Configurations(); // <<<<This is the change i made>>>>
// Go to URL
driver.get(ConfigPropertiesLoader.getApplicationURL());
//Enter Username
driver.findElement(By.xpath(OR_PropertiesLoader.userNameBoxEle()));
driver.findElement(By.xpath(OR_PropertiesLoader.userNameBoxEle())).clear();
driver.findElement(By.xpath(OR_PropertiesLoader.userNameBoxEle())).sendKeys(Username);
I'll figure out how Mystical secrets of Java one day

org.powermock.api.mockito.ClassNotPreparedException in Static class mocking

I am writing a unit test to mock a static method in the verticle but getting ClassNotPreparedException always. I think that its only possible to mock this way if only the class is static, but i have non static class. What am i missing?
I have tried various solutions like using #rule or #PowerMockIgnore
//myVerticleTest.java
package com.blabla.me.verticles;
import static com.google.common.truth.Truth.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.vertx.core.Vertx;
import io.vertx.junit5.VertxTestContext;
import io.vulpx.VulpxTestBase;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.runner.RunWith;
import com.blabla.me.verticles.AdditionalInformationCardVerticle;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.junit.Rule;
import com.blabla.me.verticles.st;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ st.class })
#PowerMockIgnore({"org.mockito.*"})
public class myVerticleTest extends VulpxTestBase {
#Rule public PowerMockRule rule = new PowerMockRule();
private Vertx vertx;
private AdditionalInformationCardVerticle dummy;
#BeforeEach
#PrepareForTest({ st.class })
public void setUp(VertxTestContext testContext) throws Exception {
vertx = Vertx.vertx();
try {
PowerMockito.mockStatic(st.class);
PowerMockito.when(st.createClient()).thenReturn("kk");
//deploying verticle
dummy = new AdditionalInformationCardVerticle();
vertx.deployVerticle(dummy, testContext.completing());
} catch (Exception e) {
System.out.println("heyyy eroorrr : " + e);
}
}
#Test
#PrepareForTest({ st.class })
public void justnormaltest() {
cla ownclass = new cla();
String k = ownclass.createfromclass();
assertThat("kk").isEqualTo(k);
}
}
// st.java
public class st {
public static String createClient() {
return "kk";
}
}
// cla.java
public class cla {
public String createfromclass() {
return st.createClient();
}
}
I expect it to run the assertion but i always get below excpetion:
"org.powermock.api.mockito.ClassNotPreparedException:
The class com.sap.me.verticles.st not prepared for test.
To prepare this class, add class to the '#PrepareForTest' annotation.
In case if you don't use this annotation, add the annotation on class or method level. "
Here:
#PrepareForTest({ st.class })
That one goes to exactly one place: in front of your test class public class myVerticleTest.
And hint: instead of adding more and more "things" to not working code: pick any good documentation, and try to follow that to the last ; in the example code (instead of assuming that adding more and more things here or there would help).
One good starting point: the official documentation on static mocking.
And of course, the usual caveat: consider not learning about PowerMock in the first place. Instead focus on writing "easy to test" code. Far too often, people think PowerMock(ito) is the answer to their problem. When their problem in reality is their inability to write "easy to test" production code.

Mocking getResource in static block with PowerMock

How to mock getResourceAsStream in the static block?
I think it is untestable.
I reviewed SO and cannot find the answer. The closes-SO-post-here does not address the issue as the call to getResourceAsAStream in the post is not from a static block.
I tried PowerMock, and run into number of limitations. First if I want to mock SomeProperties.class.getResourceAsStream - the static block will execute, as I will need to refer to the class itself. I can suppress static block to prevent doing so, but this will prevent me from getting the static block to execute at all. The solution would be to postpone the execution of the static block until after someProperties.class.getResourceAsStream is mocked.
I do not think it is possible though.
It seems that this code is purely untestable;
Any other ideas?
Here is the code [and a link to GITHUB]:
package com.sopowermock1;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SomeProperties {
private static Properties props = new Properties();
static {
InputStream is = SomeProperties.class.getResourceAsStream("/some.properties");
try {
props.load(is);
System.out.println("Properties.props.keySet() = " + props.keySet());
} catch (IOException e) {
// How test this branch???
System.out.println("Yes. We got here.");
throw new RuntimeException(e);
}
}
private SomeProperties() {}; // to makes life even harder...
public static String getVersion() {
return props.getProperty("version");
}
}
And here is the test GITHUB Link
package com.sopowermock1;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.sopowermock1.SomeProperties;
#RunWith(PowerMockRunner.class)
#PrepareForTest(SomeProperties.class)
// This will prevent running static block completely:
// #SuppressStaticInitializationFor("com.sopowermock1.SomeProperties")
public class SomePropertiesTest {
#Mock
private static InputStream streamMock;
#Before
public void setUp() {
MockitoAnnotations.initMocks(SomeProperties.class);
System.out.println("test setUp");
}
#Test(expected = RuntimeException.class)
public void testStaticBlock() {
PowerMockito.mockStatic(SomeProperties.class); // this will mock all static methods (unwanted as we want to call getVersion)
// This will cause static block to be called.
PowerMockito.when(SomeProperties.class.getResourceAsStream("/some.properties")).thenReturn(streamMock);
SomeProperties.getVersion();
}
}
Any ideas?. Full GITHUB source is here.
as mention in How to mock getResourceAsStream method using PowerMockito and JUnit?, use Extract Delegate , then mock the delegate class such as XXStreamFetcher, and then you can test it.

Spock order tests by packages

He,everyone! My tests are running by jenkins from general package. Can I set test package in spock which will be runnning first and if in this package will not passed any of test the other tests should be skipped. I saw examples like this:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({TestJunit1.class, TestJunit2.class})
public class JunitTestSuite {
}
But maybe spock has solution where I can use packages instead enum of each classes, because I have many test classes in other many packages.
Also after i used runner
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
The main thread doesnt stop. I dont know why.
I want to do something like that:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({com.example.test.*.class})
public class JunitTestSuiteFirst {
}
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({com.example.otherTest.*.class, com.example.otherTests2.*.class})
public class JunitTestSuiteFirst {
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
if(result.wasSuccessful()){
JUnitCore.runClasses(JunitTestSuite.class);
}else {
System.out.println("Build failed");
}
}
}
Or maybe exist more simple solution of this task. Thanks.
Anything you can work out inside your unit testing framework isn't going to be pretty. This is because unit tests are supposed to be independent from each other, with that mindset there won't be strong support for configuring the order of tests. As such your best bet is to look for your solution in your build tools (Ant, Maven, Gradle, etc).
The following gradle snippet sets up 2 different sets/directories of unit tests. With the command gradle test integrationTest build the tests under src/integration will only run if all the tests under src/test pass.
sourceSets {
integrationTest {
java {
srcDirs = ['src/integration']
}
groovy {
srcDirs = ['src/integration']
}
resources.srcDir file('src/integration/resources')
}
test {
java {
srcDirs = ['src/test']
}
groovy {
srcDirs = ['src/test']
}
}
}

Minecraft Bukkit Events

I'm trying to get into bukkit programming for minecraft, but for some reason I'm stuck with events. Here's my code:
Main class file:
package com.plugin1;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
//import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
public class Plugin extends JavaPlugin {
public int songStage;
public static Plugin plugin;
public void OnEnable () {
PluginDescriptionFile pluginDesc = getDescription();
Logger logger = getLogger();
plugin = this;
registerEvents(this, new BlockBreak());
logger.info(pluginDesc.getName() + " is enabled! (V. " + pluginDesc.getVersion() + ")");
}
public void OnDisable () {
PluginDescriptionFile pluginDesc = getDescription();
Logger logger = Logger.getLogger("Plugin");
plugin = null;
logger.info(pluginDesc.getName() + " is disabled! (V. " + pluginDesc.getVersion() + ")");
}
public static void registerEvents(org.bukkit.plugin.Plugin plugin, Listener... listeners) {
for (Listener listener : listeners) {
Bukkit.getServer().getPluginManager().registerEvents(listener, plugin);
}
}
public static Plugin getPlugin() {
return plugin;
}
}
Event class file:
package com.plugin1;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
public class BlockBreak implements Listener {
#EventHandler(priority = EventPriority.HIGH)
public void OnBlockBreak (BlockBreakEvent e) {
Player p = e.getPlayer();
p.sendMessage("Block broken.");
}
}
Basically, this returns no errors. I've gone through console and there's nothing. When I break a block, literally nothing happens!
I've tried a few of things: I've gone through it, tried multiple video tutorials and tried a text tutorial on the minecraft forums but still nothing. I also contacted a server owner who codes bukkit plugins, but he couldn't fix this...
If there's anyone who can help me with this, PLEASE LET ME KNOW!!!!
Thanks in advance!
Here is a code example to start the server in a process:
package me.Nightfighter001.GlobalSystem.Listener;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import me.Nightfighter001.GlobalSystem.Main.main;
public class Join implements Listener {
public Join(main main) {
plugin = main;
plugin.getServer().getPluginManager().registerEvents(this, main);
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent ev) {
ev.setJoinMessage("");
}
main plugin = main.getPlugin();
}
I think you aren't registering the Listeners in the right way...
Try this code and tell me if it works... I'm really wanting to help you
First of all don't use "Plugin" as the name for your Main Class... Use "Main" instead.
Enable:
public class Main extends JavaPlugin {
public void onEnable() {
Bukkit.getPluginManger().registerEvents(new Join(this),this);
}
}
Listener:
public class Join implements Listener {
private Main plugin;
public Join(Main plugin) {
this.plugin = plugin;
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent ev) {
ev.setJoinMessage("Just another test");
}
}
Hope it works...
I've tested your code and it really doesn't work. I think your Eventregistration isn't working. For my plugins I use this in the mainClass:
package me.Nightfighter001.GlobalSystem.Main;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import me.Nightfighter001.GlobalSystem.Listener.Join;
public class main extends JavaPlugin {
public static main getPlugin() {
return plugin;
}
private static main plugin;
#Override
public void onEnable() {
plugin = this;
new Join(this);
ConsoleCommandSender console = Bukkit.getConsoleSender();
console.sendMessage(new StringBuilder("\247c[\2476GlobalSystem\247c] \247bVersion \247c")
.append(getDescription().getVersion()).append(" \247bdes Plugins wurde aktiviert!").toString());
console.sendMessage(
"\247c[\2476GlobalSystem\247c] \247bDieses Plugin darf nur benutzt werden, wenn der Entwickler \247cNightfighter001 \247bes erlaubt!");
return;
}
#Override
public void onDisable() {
ConsoleCommandSender console = Bukkit.getConsoleSender();
console.sendMessage(new StringBuilder("\247c[\2476GlobalSystem\247c] \247bVersion \2474")
.append(getDescription().getVersion()).append(" \247bdes Plugins wurde deaktiviert!").toString());
}
}
And in the EventClass:
package me.Nightfighter001.GlobalSystem.Listener;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import me.Nightfighter001.GlobalSystem.Main.main;
public class Join implements Listener {
public Join(main main) {
plugin = main;
plugin.getServer().getPluginManager().registerEvents(this, main);
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent ev) {
ev.setJoinMessage("");
}
main plugin = main.getPlugin();
}
As you can see in my example I use the PlayerJoinEvent, but it also works with the BlockBreakEvent. I hope this helps :) And sorry for my bad English ;D
Your code will work if you don't capitalize the names of the onEnable (and onDisable) methods. onEnable and OnEnable are two different methods since java is case sensitive, and since you're trying to override specific methods in the JavaPlugin super class, you'll need to spell them the exact same way.
Common convention is, as far as I know, that you start your methods with lowercase letters anyway though. The #Override annotation is very useful in catching these kinds of bugs, because it lets the compiler know that you mean to override an existing method, and if that method doesn't exist (for example if you misspelled the name or added different parameters), it will alert you (it also lets anyone reading the code immediately know you're overriding an existing method or implementing an interface).

Categories