How to understand AssertThat (JUnit)? - eclipse

To understand JUnit, I have written the following code. In particular, I am interested in the assertThat()-method.
package test;
public class Equals {
private String x ;
public Equals(String a){
this.x = a;
}
public Equals equals(Equals x ){
return x;
}
}
Then I make a test class to test the equals()-method.
package test;
import static org.junit.Assert.*;
import org.hamcrest.Matcher;
import org.junit.Test;
public class EqualsTest {
#Test
public void testEquals() {
Equals t1 = new Equals("test");
assertThat(t1, t1.equals("test"));
}
}
Eclipse underlines assertThat with red and recommends: Create method assertThat(Equals, boolean).
The other assert-methods like assertEquals() and so on are quite straightforward, but this one is not so intuitive for me. I do not understand that. Please help.
best regards,

You must use some matcher with this method, not a boolean.
For instance, you can use the is matcher for your purpose:
assertThat("this string", is("this string"));
Take a look at this : http://tutorials.jenkov.com/java-unit-testing/matchers.html

assertThat is part of the Hamcrest assertion library. Please have a look at Hamcrest's web site: http://hamcrest.org/JavaHamcrest/

Related

the usage Java RealVector

I need help to understand how to use the abstract class org.apache.commons.math3.linear.RealVector of java.lang.Object in my program.
I have three classe, that should be using it. A Point, a Simplex and a Triangle.
The Simplex-Class should use the methods of the RealVector class to calculate the perimeter of an object, like triangle.
import java.lang.Object.*;
package org.apache.commons.math3.linear;
import org.apache.commons.math3.linear.RealVector.Entry;
import org.junit.Assert;
public class Point
{
private int dimension;
private double[] values;
private RealVector rv;
public Point(int d, double... values) {
try {
this.dimension = d;
this.values = values;
} catch (IllegalArgumentException ex) {
System.out.println("Bad Arguments");
}
}
public double get (int i) {
return values[i];
}
public int dim() {
return dimension;
}
}
When I compile that I get an error:
You have changed the package statement to a package which does not
exist in this project.
So the question is: how to use the RealVector class in my program?
Let's focus on the first lines of your code:
import java.lang.Object.*;
package org.apache.commons.math3.linear;
import org.apache.commons.math3.linear.RealVector.Entry;
import org.junit.Assert;
It has many problems:
The package declaration must come before the imports
You shouldn't put your own class into the package org.apache.commons.math3.linear. Put it inside your own package, named after your company/organization. You're not writing for the apache foundation.
import java.lang.Object.*; makes no sense. Object is a class, not a package. So you can't import all the classes inside java.lang.Object. And you don't need to import any class from java.lang: they're imported implicitly.
import org.apache.commons.math3.linear.RealVector.Entry;: you're never using this Entry class in your class. You're using the RealVector class, so that's the class you should import (although you're not really using it: you just have a private fiel of that type, which is never initialized not read, and is thus useless).
import org.junit.Assert;: you're not using this Assert class in your code either, so it shouldn't be imported. That class, BTW, is used to implement unit tests. It should be imported in unit tests, but not in production classes.
Start by fixing all this, and then ask aother question if you still have a compilation error, mentioning the exact and complete error. Make sure the jar file of the math3 apache library is in the classpath of your project: it's not bundled with the JDK, so you need to add it to the project.

Interface pointers C++

I can't express my question in words. Please look the code below, I hope you will understand my question.
I have a class and an interface as shown below.
class MyInterface
{
public:
virtual ~MyInterface(){}
virtual void print() = 0;
};
class MyClass : public MyInterface
{
public:
MyClass(){}
~MyClass(){}
void print()
{
printf("Hello World\n");
}
};
Now here's my question.
MyClass* myclass = new MyClass();
myclass->print(); //will print "Hello World"
MyInterface* pMyInterface = (MyInterface*)myclass;
pMyInterface->print();
Will the second call print Hello World as well? If yes, then why?
One note is that you do not need to explicitly cast to an accessible base class, like you do in MyInterface* pMyInterface = (MyInterface*)myclass;. It is an implicit conversion from a pointer/reference to a derived class to that of an accessible base class.
In fact, such casting may introduce bugs if the classes are unrelated.
Find more details in virtual function specifier.

Mock assertEquals not found

I am new to Mockito and need to learn it for work.
I made a very simple class that has one method that returns a string.
I then made the following test class in eclipse.
import static org.junit.Assert.*;
import org.junit.Test;
import org.mockito.Mockito;
public class No_1Test {
#Test
public void testNo_1() {
No_1 myTest = Mockito.mock(No_1.class);
Mockito.when(myTest.HelloWorld()).thenReturn("Hello World");
String result = myTest.HelloWorld();
Mockito.assertEquals("Hello World", myTest.HelloWorld());
}
}
My understanding of what I have made so far is:
I made a mock class of my No_1 class.
I specified that whenever the HelloWorld() method is called it should return the string ("Hello World")
I stored the results of HelloWorld() into the variable result (which should be "Hello World")
I want to assert that it does what it was meant to do.
The problem is that in eclipse it says that the assertEquals method is undefined for Mockito.
Can someone please point out where I am going wrong here.
You are getting the error like assertEquals method is undefined for mockito because we can't use mockito as in mockito.assertEquals as in your codes try changing it with junit.assertEquals()
And What my experience on mockito says that you should avoid mock classes of the same project,we use to mock classes for which we are dependent on other projects or module,so don't mock No_1 class in your codes and try these codes::
import static org.junit.Assert.*;
import org.junit.Test;
import org.mockito.Mockito;
public class No_1Test {
#Test
public void testNo_1() {
Mockito.when(myTest.HelloWorld()).thenReturn("Hello World");
Junit.assertEquals("Hello World", myTest.HelloWorld());
}
}
And mockito is for mocking java classes or method results but try using junit for your testing as in junit.assertequals

Losing type element when serializing object inside ArrayList to XML

I seem to be experiencing a problem when using Jackson to serialize to XML. My code is below:
TEST CONTAINER
package com.test;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TestContainer {
private String testContainerID;
private String testContainerMessage;
private ArrayList<TestChild> testContainerChildren;
#JsonProperty("TestContainerID")
public String getTestContainerID() {
return testContainerID;
}
#JsonProperty("TestContainerID")
public void setTestContainerID(String testContainerID) {
this.testContainerID = testContainerID;
}
#JsonProperty("TestContainerMessage")
public String getTestContainerMessage() {
return testContainerMessage;
}
#JsonProperty("TestContainerMessage")
public void setTestContainerMessage(String testContainerMessage) {
this.testContainerMessage = testContainerMessage;
}
#JsonProperty("TestContainerChildren")
public ArrayList<TestChild> getTestContainerChildren() {
return testContainerChildren;
}
#JsonProperty("TestContainerChildren")
public void setTestContainerChildren(ArrayList<TestChild> testContainerChildren) {
this.testContainerChildren = testContainerChildren;
}
}
TESTCHILD
package com.test;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
#JsonRootName(value="TestChild")
public class TestChild {
private String testChildID;
private String testChildMessage;
#JsonProperty("TestChildID")
public String getTestChildID() {
return testChildID;
}
#JsonProperty("TestChildID")
public void setTestChildID(String testChildID) {
this.testChildID = testChildID;
}
#JsonProperty("TestChildMessage")
public String getTestChildMessage() {
return testChildMessage;
}
#JsonProperty("TestChildMessage")
public void setTestChildMessage(String testChildMessage) {
this.testChildMessage = testChildMessage;
}
}
USE
Serialization:
XmlMapper xm = new XmlMapper();
TestContainer tc = xm.readValue(sb.toString(), TestContainer.class);
Deserialization:
System.out.println(xm.writeValueAsString(tc));
tc = xm.readValue(sb.toString(), TestContainer.class);
What I'm doing is loading an XML file from a folder on the classpath and putting the contents of the file into a StringBuffer. The problem is the generated XML for the collection of objects. When writing the XML, I want something like:
<TestContainerChildren><TestChild><...(Element Details)...></TestChild></TestContainerChildren>
but I'm getting:
<TestContainerChildren><TestContainerChildren><...(Element Details)...><TestContainerChildren></TestContainerChildren>
I'm not sure what I'm missing, here. I have no problem with the JSON part of the serialization/deserialization, only the XML. I've tried using both Jackson and JAXB annotations to turn off wrapping, I have tried using the following annotations:
#JsonRootName
#JsonProperty
#JacksonXmlElementWrapper
#JacksonElement
#XmlElementWrapper
#XmlElement
I'm pretty sure this is something stupid on my part, but any help would be most appreciated.
Ok, couple of notes. First, #JsonRootName only affects name used for the root of XML document, as name implies. So it is not used for TestChild. Second, it sounds like you want to use so-called "unwrapped" output for Lists, omitting element for property that contains List elements. This is doable with:
#JacksonXmlElementWrapper(useWrapping=false)
#JsonProperty("TestContainerChildren")
public ArrayList<TestChild> getTestContainerChildren() { ... }
since default setting is to use wrapper (this is different from JAXB, where unwrapped is the default). Or, if you want to change this globally to assume unwrapped as default, you can change the defaults via XmlModule:
JacksonXmlModule module = new JacksonXmlModule();
// to default to using "unwrapped" Lists:
module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper(module);
Hope this helps!
I got this working by using the following annotations above the variable declaration:
#JacksonXmlElementWrapper(localName="[insert collection name]")
#JacksonXmlProperty(localName="[insert collection element name]")
This was a simple case of RTFM, as it's documented here.

Writing to stdout from an Eclipse plugin

My aim is to extend the eclipse QuickFix component and automate the process of solving syntax errors. Basically, the QuickFix component provides a list of solutions and my task is to select the best possible fix and apply it to the buggy code. But, for now I've been requested to print the resolutions for a marker in the console. I've tried to work out a tutorial and I'm kind of stuck right now. The tutorial I've tried to workout is: http://www.informit.com/articles/article.aspx?p=370625&seqNum=21
I've first added the extension in my plugin.xml file
<extension point="org.eclipse.ui.ide.markerResolution">
<markerResolutionGenerator
markerType="org.eclipse.core.resources.problemmarker"
class="org.eclipse.escript.quickfix.QuickFixer"/>
</extension>
Then i have created the two classes QuickFixer and QuickFix.
package quickfixer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.IMarkerResolutionGenerator;
class QuickFixer implements IMarkerResolutionGenerator {
public IMarkerResolution[] getResolutions(IMarker arg0) {
try {
Object problem = arg0.getAttribute("Whatsup");
return new IMarkerResolution[] {
new QuickFix("Fix #1 for "+problem),
new QuickFix("Fix #2 for "+problem),
};
} catch(CoreException e) {
return new IMarkerResolution[0];
}
}
}
then the class QuickFix:
package quickfixer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IMarkerResolution;
public class QuickFix implements IMarkerResolution {
String label;
QuickFix(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void run(IMarker arg0) {
MessageDialog.openInformation(null, "QuickFix Demo",
"This quick-fix is not yet implemented");
System.out.println("Label: " + label);
}
}
I've managed to correct all the errors i encountered and then i have run the plugin.
I have not been able to get the label printed out in the console.Any suggestions???...
Using System.out is not a good idea. Check the relevant FAQ on why
you should avoid using standard output or standard error in your
plug-in
and use proper logging (or the debugger).