JBehave-Junit-Runner throwing NullPointerException - java

I am new to JBehave and am attempting to use the JBehave-JUnit-Runner to display test results nicely in JUnit in Eclipse Luna (on Ubuntu 12.04). I am using JBehave-JUnit-Runner 1.1.2, JUnit 4.12-beta-1 and JBehave-core 4.0-beta-9. When I right-click on my story file and 'Run as JUnit Test' all is well. However, when I put the #RunWith(JUnitReportingRunner.class) at the top of my story class as required for JBehave-JUnit-Runner, I get the following error:
java.lang.RuntimeException: java.lang.NullPointerException
at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.run(JUnitReportingRunner.java:80)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NullPointerException
at de.codecentric.jbehave.junit.monitoring.JUnitScenarioReporter.afterStory(JUnitScenarioReporter.java:114)
at org.jbehave.core.reporters.DelegatingStoryReporter.afterStory(DelegatingStoryReporter.java:49)
at org.jbehave.core.reporters.ConcurrentStoryReporter.afterStory(ConcurrentStoryReporter.java:120)
at org.jbehave.core.embedder.PerformableTree.performBeforeOrAfterStories(PerformableTree.java:399)
at org.jbehave.core.embedder.StoryManager.performStories(StoryManager.java:102)
at org.jbehave.core.embedder.StoryManager.runStories(StoryManager.java:93)
at org.jbehave.core.embedder.StoryManager.runStoriesAsPaths(StoryManager.java:74)
at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:204)
at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.run(JUnitReportingRunner.java:78)
... 6 more
Here is my utility class for testing. One method, very basic:
package org.felimar;
public abstract class StringManipulation
{
public static boolean stringBlank(final String src)
{
return src.matches("^\\s*$"); //$NON-NLS-1$
}
}
The story file for JBehave:
Utilities for managing character strings
Narrative:
In order to easily manipulate and investigate character strings
As a development team
I want to use a group of string-related utilities
Scenario: A string contains zero or more characters
Given a source string with value <value>
Then the method should return <return>
Examples:
|value|return|
|""|true|
|" "|true|
|"Normal Non-Blank"|false|
The steps class:
package org.felimar.steps;
import static org.felimar.StringManipulation.stringBlank;
import org.felimar.StringManipulation;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
public class StringManipulationSteps
{
private String m_srcString;
public String getSrcString()
{
return m_srcString;
}
#Given("a source string with value $value")
public void givenValue(#Named("value") final String srcString)
{
setSrcString(srcString);
}
public void setSrcString(final String srcString)
{
m_srcString = srcString;
}
#Then("the method should return $value")
public void stringBlankRtrns(#Named("value") final boolean isBlank)
{
if (stringBlank(getSrcString()) != isBlank)
throw new RuntimeException("stringBlank did not determine *" +
getSrcString() + "* was " + isBlank);
}
}
And finally, the story class:
package org.felimar.stories;
import static java.util.Arrays.asList;
import static org.jbehave.core.reporters.Format.CONSOLE;
import static org.jbehave.core.reporters.Format.TXT;
import java.util.List;
import org.felimar.StringManipulation;
import org.felimar.steps.StringManipulationSteps;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.junit.runner.RunWith;
import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;
#RunWith(JUnitReportingRunner.class)
public class StringManipulationStories extends JUnitStories
{
public StringManipulationStories()
{
super();
super.useConfiguration(
new MostUsefulConfiguration().useStoryReporterBuilder(
new StoryReporterBuilder().withDefaultFormats().withFormats(
CONSOLE, TXT)));
}
#Override
public InjectableStepsFactory stepsFactory()
{
return new InstanceStepsFactory(configuration(),
new StringManipulationSteps());
}
#Override
protected List<String> storyPaths()
{
return asList("org/felimar/stories/StringManipulationStories.story");
}
}
Are there any obvious errors in any of the code, or should I step back from using the beta libraries?

I found the problem was with the JUnit-4.12-beta-1. I had my Gradle build script set to 4.+, so I changed it to specify 4.11 and the problem disappeared. The JBehave-core 4.0-beta-9 seems to work just fine, so I left that in place.
I also experimented with using JUnitReportingRunner.recommandedControls(configuredEmbedder()); as the last line of the constructor, but it actually threw up an extra error.
My thanks to Andreas for his helpful suggestions - they were very much appreciated and ultimately helped me solve my problem.
Kind regards,
Flic

Related

Item textures are pink/black

I've tried to modify minecraft by adding a new item called "uranium". Therefore I created the class "Trauma.java" in the main package and a few other classes listed below.
All packages and classes:
Package Explorer
Trauma.java
package main;
import items.ItemUranium;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import proxy.ServerProxy;
#Mod(modid = Trauma.MODID)
public class Trauma {
public static final String MODID = "Trauma";
#SidedProxy(clientSide = "proxy.ClientProxy", serverSide = "proxy.ServerProxy")
public static ServerProxy proxy;
public static ItemUranium uranium = new ItemUranium();
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
GameRegistry.register(uranium);
}
#EventHandler
public void init(FMLInitializationEvent event) {
proxy.registerClientStuff();
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
}
BasicItem.java
package items;
import net.minecraft.item.Item;
public class BasicItem extends Item {
public BasicItem(String name) {
setUnlocalizedName(name);
setRegistryName(name);
}
}
ItemUranium.java
package items;
public class ItemUranium extends BasicItem {
public ItemUranium() {
super("uranium");
}
}
ClientProxy.java
package proxy;
import items.BasicItem;
import main.Trauma;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
public class ClientProxy extends ServerProxy {
#Override
public void registerClientStuff () {
registerItemModel(Trauma.uranium);
}
public static void registerItemModel(BasicItem item) {
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item, 0, new ModelResourceLocation(Trauma.MODID + ":" + item.getRegistryName(), "inventory"));
}
}
ServerProxy.java
package proxy;
public class ServerProxy {
public void registerClientStuff() {}
}
uranium.json
{
"parent": "item/generated",
"textures": {
"layer0": "Trauma:items/uranium"
}
}
uranium.png
ingame
Also I don't know why the item in inventory isn't called uranium...
I spent two hours on fixing the problem and it didn't help so it would be really nice if somebody of you may help me.
Thanks :)
Don't use the Model Mesher:
The model mesher is Vanilla (Mojang) code and using it correctly has always been finicky and unreliable, failing if you called it too early and failing if you called it too late. So Forge added the ModelLoader class to resolve that problem.
Replace this line:
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(...)
With this line:
ModelLoader.setCustomModelResourceLocation(...)
The ... contents are identical.
Second, depending on what version of Minecraft you're using, you should...:
Stop using GameRegistry.Register
Instead use the RegistryEvent.Register<T> events (where <T> will be <Block> to register blocks, <Item> to register items, etc)
Register your models in the ModelRegistryEvent and no where else.
This event is #SideOnly(CLIENT) and can be subscribed to in your client proxy, avoiding the need to forward references through your proxy class. Eg. I do it like this, where lines 197-199 is the most common scenario needed, where the array is populated during the item registration event. The rest of that method handles the custom state mappers and custom mesh definitions that are used by only a handful of items/blocks and not relevant here.
Include your Mod ID in your unlocalized name. The best way to do this would be setUnlocalizedName(getRegistryName().toString());
See also the Forge documentation on events.

Why is getItemInHand being crossed out (see image below)

I am new to creating minecraft plugins, however not new to programming, I am following a tutorial very thoroughly, the video has good ratings so it is trusted, when watching the video the guy has no problems what so ever (Youtube video on developing minecraft plugins) , so I did some research into solutions but always the line through the code.
Eclipse gives me the option for: #SuppressWarnings("deprecation") which allows the code to be used still but I would rather have no need of that usage.
Basically my question is why is there the need of the line going through the code and how do I find a solution to get rid of it.
Main class:
package com.jc1;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Core extends JavaPlugin
{
public Permission pPermission = new Permission("playerAbilities.allowed");
#Override
public void onEnable()
{
new BlockListener(this);
PluginManager pm = getServer().getPluginManager();
pm.addPermission(pPermission);
}
#Override
public void onDisable()
{
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if(cmd.getName().equalsIgnoreCase("giveitems") && sender instanceof Player)
{
Player p = (Player) sender;
if(p.hasPermission("playerAbilities.allowed"))
{
p.setItemInHand(new ItemStack(Material.DIAMOND_BOOTS));
}
return true;
}
return false;
}
}
Secondary class:
package com.jc1;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class BlockListener implements Listener
{
public BlockListener(Core plugin)
{
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
#EventHandler
public void onBlockPlace(BlockPlaceEvent e)
{
Player p = e.getPlayer();
if(!p.hasPermission("playerAbilities.allowed"))
{
e.setCancelled(true);
}
}
}
The method is deprecated, meaning that it is not recommended to be used anymore and is most likely replaced with another method.
Methods that are deprecated may still work as intended.
A simple search for the method reveals (this) documentation, stating:
players can duel wield now use the methods for the specific hand instead
which referes to the #see references:
getItemInMainHand() and getItemInOffHand().
Use this:
player.getInventory().getItemInMainHand()
Instead of:
player.getItemInHand()
Hope this helps! :D

Textures do not appear

I am trying to add a texture to an item, yet the texture just doesn't appear. I have the texture made, and in the right file directory, but while in game it doesn't display. Thus, I think it's an error in my code.
For the whole class file, see below:
package Moonstone;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.EnumHelper;
#Mod(modid = "ms", name = "Moonstone", version = "1.0")
public class MoonstoneMain {
public static Item moonstone;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
//All init
moonstone = new Moonstone().setUnlocalizedName("Moonstone").setTextureName("moonstone").setMaxStac kSize(64);
GameRegistry.registerItem(moonstone, moonstone.getUnlocalizedName().substring(5));
}
#EventHandler
public void init(FMLInitializationEvent event) {
//Proxy, TileEntity, entity, GUI and packet registering
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
public static CreativeTabs tabMoonstone = new CreativeTabs("tabMoonstone"){
#Override
public Item getTabIconItem(){
return new ItemStack(Items.stick).getItem();
}
};
}
For just the item, look below-
moonstone = new Moonstone().setUnlocalizedName("Moonstone").setTextureName("moonstone").setMaxStackSize(64);// I have tried with ms:moonstone and without, both don't work.
GameRegistry.registerItem(moonstone, moonstone.getUnlocalizedName().substring(5));
Recommended changes but not necessary:
First:
When registering the item you should remove the .substring(5),
having this in will name the item "Moons" instead of "Moonstone".
Second:
unlocalized names should always be lowercase and should be formatted
as modid_itemname
Third:
Package names should be lowercase, package moonstone
Fourth:
Your should make a Refstrings.java file and put the modid, version and name in it
package Moonstone
public RefStrings{
public static String NAME = "Moonstone";
public static String MODID = "ms";
public static String VERSION = "1.0";
}
Necessary changes:
Your setTextureName should be passed "ms:moonstone"
You didn't post your folder structure but it should look like this:
src/main/java/Moonstone/MoonstoneMain.java
src/main/resources/assests/ms/textures/items/moonstone.png
it is possible that some of the recommend changes will be what fixes the problem, minecraft can be a bit finicky with naming.

My bukkit plugin won't load

I'm relatively new to making bukkit plugins, and i have a basic understanding of java. My plugin won't work. From what i see on other forums, this is a common error but none of the solutions have worked.
Here is my error:
[16:18:19 ERROR]: Could not load 'plugins/MtgCraft.jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: Cannot find main class `me.sporech.MagictgCraft'
My plugin.yml:
name: MtgCraft
main: me.sporech.MagictgCraft
version: 1.8
author: Sporech
description: A basic plugin
My code is:
package me.sporech;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class MagictgCraft extends JavaPlugin {
public static MagictgCraft plugin;
#Override
public void onEnable(){
getLogger().info("this is the plugin doing it");
}
#Override
public void onDisable(){
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("hello") && sender instanceof Player) {
Player player = (Player) sender;
player.sendMessage("Hello, " + player.getName() + "!");
return true;
}
return false;
}
#EventHandler
public void onPlayerInteractBlock(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.getItemInHand().getType() == Material.STICK) {
player.getWorld().strikeLightning(player.getTargetBlock((Set<Material>) null, 200).getLocation());
}
}
}
The error is with your plugin.yml, not your code. Ensure that the plugin.yml is included in the default package and is inside your jar after exporting/zipping it.
It says that your description is invalid ("InvalidDescriptionException"); it may be too short, but that is just a guess. If lengthening your description does not work, try following the description with a ">" and a line break, then writing the description on the next line preceded by at least 8 spaces as shown in the example below from one of my plugins:
description: >
This super simple plugin has so many features your head may just implode.
The above works in my plugins, though honestly it should not be necessary. Still, it's worth a try.
EDIT:
For future readers who don't want to sift through comments, the problem here was that the plugin.yml was not included in the "src" folder or in the default package of the exported jar. Always make sure your plugin.yml is in your exported jar in the default package!

FEST: How to use the NoExitSecurityManager properly?

I starting to use FEST to help me to perform unit test on my Java Swing GUI.
For now, I managed to get through the documentation (mostly deprecated) and help me by looking at the Javadoc and the code.
Right now I am stuck on a problem while using the NoExitSecurityManager. The documentation is quite out dated but we can understand the big lines of it.
I simply try to test if my "Quit" MenuItem is working well in my GUI. So, I need to block the System.exit(0) and map the exit status of the program to a JUnit test.
Here is a simplified code I use to perform the test (the tested class is GraphicalUserInterface).
import org.junit.Test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.edt.GuiQuery;
import org.fest.swing.edt.GuiActionRunner;
import org.fest.swing.fixture.FrameFixture;
import org.fest.swing.junit.testcase.FestSwingJUnitTestCase;
import org.fest.swing.security.NoExitSecurityManagerInstaller;
public class GraphicalUserInterfaceTest extends FestSwingJUnitTestCase {
private static FrameFixture gui;
private static NoExitSecurityManagerInstaller noExitSecurityManagerInstaller;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
NoExitSecurityManagerInstaller.installNoExitSecurityManager(new ExpectExitSuccess());
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
noExitSecurityManagerInstaller.uninstall();
}
#Override
protected void onSetUp() {
gui = new FrameFixture(robot(), createNewGUI());
gui.show();
}
#RunsInEDT
private GraphicalUserInterface createNewGUI() {
return GuiActionRunner.execute(new GuiQuery<GraphicalUserInterface>() {
protected GraphicalUserInterface executeInEDT() {
return new GraphicalUserInterface();
}
});
}
#Test
public final void testFileMenuQuitMenuItem() {
gui.menuItemWithPath("File", "Quit").click();
}
}
The ExitCallHook are coded like this (you can guess the other one easily).
import static org.junit.Assert.assertTrue;
import org.fest.swing.security.ExitCallHook;
public final class ExpectExitSuccess implements ExitCallHook {
#Override
public void exitCalled(int status) {
assertTrue(status == 0);
}
}
All the tests are performed well and everything seems to be ok except that I get a java.lang.NullPointerException at the end.
So, I wonder what did I do wrong (or what can I improve to not get this nullpointer exception at the end of the test).
I found the solution in the code. In fact, the proper way to do it is the following:
#Test
public final void testFileMenuQuitMenuItem() {
NoExitSecurityManagerInstaller noExitSecurityManagerInstaller =
NoExitSecurityManagerInstaller.installNoExitSecurityManager(new ExpectExitSuccess());
gui.menuItemWithPath("File", "Quit").click();
noExitSecurityManagerInstaller.uninstall();
}
This way prevent to pollute each test with a NoExitSecurityManager.

Categories