I am following a tutorial and trying to parse some simple code snippet using ANTLR but I cannot do so, I get a lot of compile time errors that I cannot resolve, I am posting a screenshot of the errors that I am getting in my IDE.
package cplusplusparser;
import java.util.ArrayList;
import java.util.List;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import cplusplusparser.CPP14Parser.AbstractdeclaratorContext;
import cplusplusparser.CPP14Parser.TranslationunitContext;
import org.antlr.v4.*;
import org.antlr.*;
import org.antlr.runtime.tree.ParseTree;
public class UppercaseMethodListener extends CPP14BaseListener {
private List<String> errors = new ArrayList<>();
// ... getter for errors
#Override
public void enterMethodDeclarator(AbstractdeclaratorContext ctx) {
TerminalNode node = ctx.Identifier();
String methodName = node.getText();
if (Character.isUpperCase(methodName.charAt(0))) {
String error = String.format("Method %s is uppercased!", methodName);
errors.add(error);
}
}
// ... getter for errors
static String javaClassContent = "public class SampleClass { void DoSomething(){} }";
static CPP14Lexer java8Lexer = new CPP14Lexer(CharStreams.fromString(javaClassContent));
static CommonTokenStream tokens = new CommonTokenStream(java8Lexer);
static CPP14Parser parser = new CPP14Parser(tokens);
static TranslationunitContext tree = parser.translationunit();
static ParseTreeWalker walker = new ParseTreeWalker();
static UppercaseMethodListener listener= new UppercaseMethodListener();
public static void main (String []args ) {
walker.walk(listener, tree);
assertThat(listener.getErrors().size(), is(1));
assertThat(listener.getErrors().get(0),
is("Method DoSomething is uppercased!"));
}
}
Related
There is error in assertEquals(), The method assertEquals(int, int) is undefined for the type TATManagementServiceTestCase.
I think this class is depricated so what is the replacement of this class and its method.My code:
package ae.edaman.tat.service;
import java.util.List;
//import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import ae.edaman.common.exception.ApplicationException;
import ae.edaman.tat.model.ClientType;
import ae.edaman.tat.model.MemCountClassification;
import ae.edaman.tat.model.WorkflowStatusMapping;
public class TATManagementServiceTestCase extends AbstractJUnit4SpringContextTests
//AbstractDependencyInjectionSpringContextTests
{
protected String[] getConfigLocations() {
setAutowireMode(AUTOWIRE_BY_NAME);
return new String[] {
"applicationContext.xml"
};
}
private TATManagementService tatManagementService;
public void testClaimsMapping() {
Exception exception = null;
List<WorkflowStatusMapping> workflowStatusList = null;
try {
WorkflowStatusMapping searchCriteria = new WorkflowStatusMapping();
searchCriteria.setServiceCode("OCT");
workflowStatusList = tatManagementService.findWorkflowStatusMapping(searchCriteria);
} catch (ApplicationException ae) {
exception = ae;
}
assert exception == null;
assertEquals(8, workflowStatusList.size());//i have error in this line and also few more method like assertnull()
}
I am not sending the complete code and if possible do give me complete dependency and method name .
Why I am getting this error?
The constructor C17PacketCustomPayload(String, byte[]) is undefined
Java Code:
package pw.cinque.ping;
import java.awt.Color;
import net.minecraft.client.Minecraft;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.C17PacketCustomPayload;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.awt.*;
import java.nio.ByteBuffer;
import org.lwjgl.input.Keyboard;
#Mod(modid = Packets.MODID, version = Packets.VERSION)
public class Packets
{
public static final String MODID = "Lower ur ping!";
public static final String VERSION = "1.0";
private static final Minecraft mc = Minecraft.getMinecraft();
private boolean textGui;
private final int textGuiKey = Keyboard.KEY_P;
private boolean reachToogle;
private final int reachKey = Keyboard.KEY_L;
#EventHandler
public void init(FMLInitializationEvent event)
{
FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
System.out.println("Intialized Reach Mod by Shiny");
}
#SubscribeEvent
public void onRender(TickEvent.RenderTickEvent e) {
if(textGui)
mc.fontRendererObj.drawStringWithShadow("Shiny", 2, 2, Color.BLACK.hashCode());
}
#SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent e) {
if(Keyboard.isKeyDown(textGuiKey)) {
textGui = !textGui;
return;
}
else if(Keyboard.isKeyDown(reachKey)) {
reachToogle = !reachToogle;
}
Packet spoofedReachPacket = manipulateReachPacket(spoofReachValue(4.2));
mc.thePlayer.sendQueue.addToSendQueue(spoofedReachPacket);
}
private Packet manipulateReachPacket(byte[] spoofedReachValue) {
return new C17PacketCustomPayload("reach", spoofedReachValue);
}
private byte[] spoofReachValue(double reachValue) {
byte[] buffer = new byte[8];
ByteBuffer.wrap(buffer).putDouble(reachValue`enter code here`);
return buffer;
}
}
I'm guessing you're getting your error here:
return new C17PacketCustomPayload("reach", spoofedReachValue);
It's saying that the constructor is undefined which means the class C17PacketCustomPayload does not have a constructor that takes a string and/or byte[] as arguments. If you created this class yourself then you need to add a method that looks like this
public C17PacketCustomPayload(String string, byte[] bytes){
//add behavior here
}
If you didn't create this class but are merely importing, then you need to look up just what parameters this constructor takes and fix it accordingly.
Why I am getting this error?
The answer is evident from these reverse engineered javadocs.
Constructors:
C17PacketCustomPayload()
C17PacketCustomPayload(java.lang.String p1, PacketBuffer p1)
In your code, the second parameter to the constructor call needs to be a PacketBuffer object, not a byte[].
//This is my Main Class here when i call methodTwo in this class i got numnodes=4 but when i tried to access methodTwo in testclass i got NullPointerException.
package Netica;
import norsys.netica.Environ;
import norsys.netica.Net;
import norsys.netica.NodeList;
import norsys.netica.Streamer;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import NeticaTestCases.HNetTest;
public class HNet {
private static long startTime = System.currentTimeMillis();
private static Net net;
private static NodeList nodes;
int numNodes;
public int methodOne() {
System.out.println("we are in first methodOne");
return 1;
}
public int methodTwo() {
numNodes = nodes.size();
System.out.println("we are in 2nd methodTwo");
return numNodes;
}
public static void main(String[] args) {
try {
// Read in the net file and get list of all nodes and also Total
// number of nodes:
net = new Net(neStreamer("DataFiles/KSA_4_Nodes_noisySum.dne"));
nodes = net.getNodes();
HNet temp = new HNet();
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());//get 4
} catch (Exception e) {
}
}
}
//this is my testclass
package NeticaTestCases;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.fail;
import Netica.HNet;
public class HNetTest {
HNet temp;
#Before
public void setUp() {
temp = new HNet ();
}
#Test
public void CheckNumNodes() {
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());
}
}
please help me out how to resolve NullPointerException in junit testcases.
Adding a statement initialising the nodes should get you rid of the exception -
#Before
public void setUp() {
temp = new HNet ();
temp.nodes = new NodeList();
}
Also, would suggest you to try and improve on few points -
Debug the difference between your main method and CheckNumNodes() test method.
Use of getters and setters
Is it possible to have a Junit rule only apply to specific tests? If so, how do I do that?
The code below exemplifies what I want to do: each time I have #Rule, I want the method below that to have the specific rule that has been annotated to run with it. I only want that rule to run with the corresponding test. I don't want anything other tests to be affected by the rule.
In this case, when I run these tests, I see that one of the tests the EmptyFileCheck, gives a File DNE does not exist, but I have used a separate annotation for that function, so I had thought that it would run with a different context, supplying the Empty, but instead DNE is till being used.
import static java.lang.System.in;
import static java.lang.System.setIn;
import static org.junit.Assert.fail;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.channels.Pipe;
import static org.hamcrest.core.AllOf.allOf;
import org.hamcrest.Matcher;
import org.hamcrest.core.AllOf;
import static org.hamcrest.Matchers.*;
import org.hamcrest.text.StringContains;
import org.hamcrest.text.StringEndsWith;
import org.hamcrest.text.StringStartsWith;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
import org.junit.runner.RunWith;
public class UnitTests {
private Mockery context = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
private main mn;
private InputStream oldIn;
private PrintStream oldOut;
private InputStream mockIn;
private InputStreamReader mockinputStream;
private PrintStream mockOut;
private BufferedReader reader;
private Expectations exp;
#Before
public void setMinimalMockingExpectations() throws IOException {
exp = new Expectations() {{ }};
mn = context.mock(main.class);
mockinputStream = context.mock(InputStreamReader.class);
oldIn = System.in;
oldOut = System.out;
mockIn = context.mock(InputStream.class);
mockOut = context.mock(PrintStream.class);
System.setOut(mockOut);
}
public void configureExpectations(boolean fileOrInput, boolean verbosity) {
exp.one(mockOut).println("Do you want to process standard (I)nput, or a (F)ile? I/F");
if (fileOrInput) { //it's a file
exp.one(mockOut).println("Enter filename: ");
} else { //it's not
}
}
#After
public void reset() {
System.setOut(oldOut);
}
#Rule
public final TextFromStandardInputStream FileNotFoundException
= new TextFromStandardInputStream("F\nDNE\n");
#Test(expected=FileNotFoundException.class)
public void EnsureFileCheckExists() throws IOException {
final String fileName = "DNE";
configureExpectations(true, false);
exp.one(mn).checkFile(fileName);
context.checking(exp);
mn.main(null);
}
#Rule
public final TextFromStandardInputStream FileReadAccessDenied
= new TextFromStandardInputStream("F\nUnderPriviledged\n");:w
#Test(expected=FileNotFoundException.class)
public void FileReadAccessDenied() throws java.io.FileNotFoundException {
final String fileName = "UnderPriviledged";
configureExpectations(true, false);
//exp.oneOf(mn).checkFile(with()); TODO: fix ME!
context.checking(exp);
mn.main(null);
}
#Rule
public final TextFromStandardInputStream EmptyFileCheck
= new TextFromStandardInputStream("F\nEmpty\n");
#Test
public void EmptyFileCheck() throws java.io.FileNotFoundException {
final String fileName = "Empty";
configureExpectations(true, false);
exp.one(mn).checkFile(fileName);
context.checking(exp);
mn.main(null);
}
}
You could have a setter in your Rule which is the first thing that gets called in the rule. Something like this, from ExpectedException:
// These tests all pass.
public static class HasExpectedException {
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
#Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
#Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
}
Any reason not to just take the code out of the #rule annotation and move it to the start of the test body?
From the examples on the PowerMock homepage, I see the following example for partially mocking a private method with Mockito:
#RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
#PrepareForTest(PartialMockClass.class)
public class YourTestCase {
#Test
public void privatePartialMockingWithPowerMock() {
PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());
// use PowerMockito to set up your expectation
PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");
// execute your test
classUnderTest.execute();
// Use PowerMockito.verify() to verify result
PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
}
However, this approach does not seem to work when the private method we wish to mock is static. I wish to create a partial mock of the below class, with the readFile method mocked:
package org.rich.powermockexample;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import static com.google.common.io.Files.readLines;
public class DataProvider {
public static List<String> getData() {
List<String> data = null;
try {
data = readFile();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
List<String> lines = readLines(file, Charset.forName("utf-8"));
return lines;
}
}
Please could someone let me know how this can be achieved?
After doing a bit more research, it seems that PowerMockito.spy() and PowerMockito.doReturn() are what is required here:
package com.richashworth.powermockexample;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
#RunWith(PowerMockRunner.class)
#PrepareForTest({DataProvider.class})
public class ResultsWriterTest {
private static List<String> mockData = new ArrayList<String>();
private ResultsWriter resultsWriter;
#BeforeClass
public static void setUpOnce() {
final String firstLine = "Line 1";
final String secondLine = "Line 2";
mockData.add(firstLine);
mockData.add(secondLine);
}
#Before
public void setUp() {
resultsWriter = new ResultsWriter();
}
#Test
public void testGetDataAsString() throws Exception {
PowerMockito.spy(DataProvider.class);
PowerMockito.doReturn(mockData).when(DataProvider.class, "readFile");
final String expectedData = "Line 1\nLine 2\n";
final String returnedString = resultsWriter.getDataAsString();
assertEquals(expectedData, returnedString);
}
}
For further details and the complete code listing, check out my blog post here: https://richashworth.com/post/turbocharge-your-mocking-framework-with-powermock/
Test class:
#RunWith(PowerMockRunner.class)
#PrepareForTest(DataProvider.class)
public class DataProviderTest {
#Test
public void testGetDataWithMockedRead() throws Exception {
mockStaticPartial(DataProvider.class, "readFile");
Method[] methods = MemberMatcher.methods(DataProvider.class, "readFile");
expectPrivate(DataProvider.class, methods[0]).andReturn(Arrays.asList("ohai", "kthxbye"));
replay(DataProvider.class);
List<String> theData = DataProvider.getData();
assertEquals("ohai", theData.get(0));
assertEquals("kthxbye", theData.get(1));
}
}
Class being tested (basically yours):
public class DataProvider {
public static List<String> getData() {
try {
return readFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
return readLines(file, Charset.forName("utf-8"));
}
}
In general, only use static mocking for classes that are beyond your control (e.g. java.io.File). Since DataProvider and readFile are your own, refactor DataProvider into a proper class (i.e. make its methods non-static), pull out readFile into a helper object and then mock that. See this answer https://stackoverflow.com/a/8819339/116509.