I am very new to JUnit testing, I am trying to test the following very simple class
public interface IItemsService extends IService {
public final String NAME = "IItemsService";
/** Places items into the database
* #return
* #throws ItemNotStoredException
*/
public boolean storeItem(Items items) throws ItemNotStoredException;
/** Retrieves items from the database
*
* #param category
* #param amount
* #param color
* #param type
* #return
* #throws ItemNotFoundException
*/
public Items getItems (String category, float amount, String color, String type) throws ItemNotFoundException;
}
This is what I have for the test but I keep getting null pointer, and another error about it not being applicable for the argument... obviously I am doing something stupid but I am not seeing it. Could someone point me in the right direction?
public class ItemsServiceTest extends TestCase {
/**
* #throws java.lang.Exception
*/
private Items items;
private IItemsService itemSrvc;
protected void setUp() throws Exception {
super.setUp();
items = new Items ("red", 15, "pens", "gel");
}
IItemsService itemsService;
#Test
public void testStore() throws ItemNotStoredException {
try {
Assert.assertTrue(itemSrvc.storeItem(items));
} catch (ItemNotStoredException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println ("Item not stored");
}
}
#Test
public void testGet() throws ItemNotStoredException {
try {
Assert.assertFalse(itemSrvc.getItems(getName(), 0, getName(), getName()));
} catch (ItemNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You're not creating an instance of the class under test, you're only declaring it as the interface. In each of your tests you should create an instance of the class under test and test it's implementation of the method. Note also, your tests should not be dependent on one another. You shouldn't rely on them running in particular order; any set up for a test should be done in the test set up method, not by another test.
Generally you want to use the AAA (Arrange, Act, Assert) pattern in your tests. The setUp (arrange) and tearDown (assert) can be part of this, but the pattern should also be reflected in each test method.
#Test
public void testStore() throws ItemNotStoredException {
// Arrange
ISomeDependency serviceDependency = // create a mock dependency
IItemsService itemSvc = new ItemsService(someDependency);
// Act
bool result = itemSrvc.storeItem(items);
// Assert
Assert.assertTrue(result);
// assert that your dependency was used properly if appropriate
}
Related
Let me explain what I exactly expecting
I have a method like the following
public void removeByObject()
{
try {
DsrCollection dsrCollection = new DsrCollection();
dsrCollection. setNuId(180);
dsrCollectionRepository.remove(dsrCollection);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Here I want to check that the particular method removeByObject() executed successfully or not(also want to involve Assert.assertEqual(dsrCollectionRepository.remove(dsrCollection),??)). So for checking the condition what should be the actual value.
Or in a more specific way what object should appear in actual value place. My requirement is like if application failed to execute dsrCollectionRepository.remove(dsrCollection) it should return the assertError message
To make removeByObject() more testable you can simply extract the code in the try block into its own method. e.g.:
public class DsrCollectionRepositoryManager /* Or whatever your class is called. */ {
/* ... */
public void removeByObject() {
try {
removeByObjectOrThrow();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
protected boolean /* or whatever your return type is */ removeByObjectOrThrow() {
DsrCollection dsrCollection = new DsrCollection();
dsrCollection.setNuId(180);
return dsrCollectionRepository.remove(dsrCollection);
}
/* ... */
}
Now you can test removeByObjectOrThrow() and see if it throws an exception or not.
If you are trying to test it where removeByObject() is called on your behalf and/or you don't want to call removeByObjectOrThrow() directly then you can subclass your unit under test. e.g.:
public class DsrCollectionRepositoryManagerTest {
#Test
public void removeObjectSuccessful() {
boolean expected = true;
DsrCollectionRepositoryManager dsrCollectionRepositoryManager = new DsrCollectionRepositoryManager() {
#Override
protected boolean removeByObjectOrThrow() {
try {
boolean actual = super.removeByObjectOrThrow();
Assert.assertEquals(actual, expected);
return actual;
} catch (Exception cause) {
String message = "`removeObject` should not have thrown an exception but did";
throw new AssertionError(message, cause);
}
}
};
dsrCollectionRepositoryManager.removeByObject();
}
#Test
public void removeObjectUnsuccessful() {
DsrCollectionRepositoryManager dsrCollectionRepositoryManager = new DsrCollectionRepositoryManager() {
#Override
protected boolean removeByObjectOrThrow() {
super.removeByObjectOrThrow();
String detailMessage = "`removeByObject` should have thrown an exception but did not";
throw new AssertionError(detailMessage);
}
};
dsrCollectionRepositoryManager.removeByObject();
}
}
As I don't know the name of your unit under test nor the type of what you want to use assertEquals with I've made things up but the idea is the same: isolate the code you want to test and test it.
Does dsrCollectionRepository.remove(obj) return a value indicating whether the removal is successful or not? I'd recommend implementing the function so it does return a boolean on a successful removal of an object, otherwise you rely on exceptions to inform you of the failure of the function.
If it already returns a boolean value just assertTrue(dsrCollectionRepository.remove(dsrCollection);
If the failure of the function throws a known exception you can use the following annotation to test the function:
#Test(expectedExceptions = MyException.class), however you then rely on the fact that only that exception can be thrown while performing that function, which is problematic if someone adds an exception that can be thrown in implementation without your knowledge.
I need to Unmarshal XML to Java Object, I have tried with below code. Its create an Object but set all value as a null. code for same:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Dispatch implements java.io.Serializable {
private Integer dispatchId;
private Order order;
/**
* #return the dispatchId
*/
public Integer getDispatchId() {
return dispatchId;
}
/**
* #param dispatchId
* the dispatchId to set
*/
public void setDispatchId(Integer dispatchId) {
this.dispatchId = dispatchId;
}
/**
* #return the order
*/
public Order getOrder() {
return order;
}
/**
* #param order
* the order to set
*/
public void setOrder(Order order) {
this.order = order;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return ""+this.dispatchId;
}
}
I have Dispatch Class with other sub class, i need to convert XML to Java Object. Code for same:
Public class UnmarshalExample {
public static void main(String[] args) {
String xmlString = "<ns1:dispatch xmlns:ns1=\"http://service.order.com\"><ns1:dispatchId>1</ns1:dispatchId><ns1:order><ns1:totalAmount>1000.0</ns1:totalAmount></ns1:order></ns1:dispatch>";
Dispatch dispatch = (Dispatch) JAXB.unmarshal(
new StringReader(xmlString), Dispatch.class);
System.out.println(dispatch);
}
}
As a output it will return null.
Can any one tell me whats wrong thing in my code?
That is odd, I pasted you code and ran and it produces dispatchId 1:
Dispatch class:
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Dispatch implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer dispatchId;
/**
* #return the dispatchId
*/
public Integer getDispatchId() {
return dispatchId;
}
/**
* #param dispatchId
* the dispatchId to set
*/
public void setDispatchId(Integer dispatchId) {
this.dispatchId = dispatchId;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return ""+this.dispatchId;
}
}
Test class
import java.io.*;
import javax.xml.bind.JAXB;
public class Test {
public static void main(String[] args) {
String xmlString = "<ns1:dispatch xmlns:ns1=\"http://service.order.com\"><ns1:dispatchId>1</ns1:dispatchId><ns1:order><ns1:totalAmount>1000.0</ns1:totalAmount></ns1:order></ns1:dispatch>";
Dispatch dispatch = (Dispatch) JAXB.unmarshal(
new StringReader(xmlString), Dispatch.class);
System.out.println(dispatch);
}
}
output is
1
The order is of the type Order. We don't see any code of this class.
This is probably the cause of it as well. You may not provide decent data for the Order to be constructed.
To see how namespaces are used: http://blog.bdoughan.com/2012/11/applying-namespace-during-jaxb-unmarshal.html
This question already has answers here:
What are reasons for Exceptions not to be compatible with throws clauses?
(4 answers)
Closed 4 years ago.
I'm running the Lip reading code on Eclipse Indigo from the following link :
https://github.com/sagioto/LipReading/blob/master/lipreading-core/src/main/java/edu/lipreading/WebFeatureExtractor.java
package main.java.edu.lipreading;
import com.googlecode.javacpp.BytePointer;
import com.googlecode.javacv.cpp.opencv_core;
import main.java.edu.lipreading.vision.AbstractFeatureExtractor;
import main.java.edu.lipreading.vision.NoMoreStickersFeatureExtractor;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.logging.Logger;
import static com.googlecode.javacv.cpp.opencv_core.CV_8UC1;
import static com.googlecode.javacv.cpp.opencv_core.cvMat;
import static com.googlecode.javacv.cpp.opencv_highgui.cvDecodeImage;
/**
* Created with IntelliJ IDEA.
* User: Sagi
* Date: 25/04/13
* Time: 21:47
*/
public class WebFeatureExtractor extends Server {
private final static Logger LOG = Logger.getLogger(WebFeatureExtractor.class.getSimpleName());
private final static AbstractFeatureExtractor fe = new NoMoreStickersFeatureExtractor();
public WebFeatureExtractor(int port) {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
addConnector(connector);
WebSocketHandler wsHandler = new WebSocketHandler() {
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new FeatureExtractorWebSocket();
}
};
setHandler(wsHandler);
}
/**
* Simple innerclass that is used to handle websocket connections.
*
* #author jos
*/
private static class FeatureExtractorWebSocket implements WebSocket, WebSocket.OnBinaryMessage, WebSocket.OnTextMessage {
private Connection connection;
public FeatureExtractorWebSocket() {
super();
}
/**
* On open we set the connection locally, and enable
* binary support
*/
#Override
public void onOpen(Connection connection) {
LOG.info("got connection open");
this.connection = connection;
this.connection.setMaxBinaryMessageSize(1024 * 512);
}
/**
* Cleanup if needed. Not used for this example
*/
#Override
public void onClose(int code, String message) {
LOG.info("got connection closed");
}
/**
* When we receive a binary message we assume it is an image. We then run this
* image through our face detection algorithm and send back the response.
*/
#Override
public void onMessage(byte[] data, int offset, int length) {
//LOG.info("got data message");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
bOut.write(data, offset, length);
try {
String result = convert(bOut.toByteArray());
this.connection.sendMessage(result);
} catch (Exception e) {
LOG.severe("Error in facedetection, ignoring message:" + e.getMessage());
}
}
#Override
public void onMessage(String data) {
LOG.info("got string message");
}
}
public static String convert(byte[] imageData) throws Exception {
opencv_core.IplImage originalImage = cvDecodeImage(cvMat(1, imageData.length, CV_8UC1, new BytePointer(imageData)));
List<Integer> points = fe.getPoints(originalImage);
if(points == null)
return "null";
String ans = "";
for (Integer point : points) {
ans += point + ",";
}
return ans;
}
/**
* Start the server on port 999
*/
public static void main(String[] args) throws Exception {
WebFeatureExtractor server = new WebFeatureExtractor(9999);
server.start();
server.join();
}
}
In the following line :
public static void main(String[] args) throws Exception {
I'm getting the following error :
Exception Exception is not compatible with throws clause in Server.main(String[])
Please help me solve this.
There are two condition you need to check.
1) when declaring a method in interface you need to add throws exception for that method and similarly with the interface implementation class where the method is implemented.
for example
service.java
#Component
public interface UserService {
User getUser(Login login) throws Exception;
}
serviceimpl.java
public User getUser(Login login)throws Exception
{
}
2) by doing the above statement the error still doesn't vanish. make sure to save both the files.
Doest the server API handle all exceptions for itself. Why not try removing the throws in your code. I know its not good programming practice but might solve the problem.
The problem is that the Server class you are extending already contains a public static void main(String[]) method that does not have the same throws declaration. I didn't take a look at it, but I'd bet that method doesn't throw anything at all.
A solution would be to remove your throws clause in your main method and rely on try-catches instead.
EDIT: Why you cannot add a different throws clause in your case.
Let's assume the following scenario:
class A {
public static void foo() throws SomeException { ... }
}
class B extends A {
public static void foo() throws DifferentException { ... }
}
The Java standard says you are hiding the A.foo() method (or at least trying to). Thing is, you're only allowed to do that if the throws clause in B.foo() is already contained in the clause of A.foo(). So for the above scenario, you're perfectly legal only if DifferentException is a subclass of SomeException. Otherwise the compiler will yell.
I had the same issue, in my case I have implemented a method from an interface that did not declared to throw an exception.
In your case, I would guess that Server class also has a main method that didn't throw an exception. To quickly solve it. I would declare Server.main to throw an exception.
This link helped me
What are reasons for Exceptions not to be compatible with throws clauses?
My question is simple. I'm trying to make a set of java.net.URLs that are public static final, so that any class can access them from any context, as these URLs won't change during runtime. However, when I try to create them, I get a compiler error telling me that I must catch or declare thrown a java.net.MalformedURLException, but that is impossible outside a method. Is there any way to circumvent such a constructor that throws a non-java.lang Throwable?
Some dummy code below to visualize my problem:
public class Main
{
public static final java.net.URL STATIC_URL = new java.net.URL("http://example.com/");
public static void main(String[] args)
{
GUI gui = new GUI();
gui.setVisible(true);
}
}
public class GUI extends java.awt.Window
{
public GUI()
{
add(new java.awt.Label(Main.STATIC_URL.toString()));
}
}
If you try to compile this, it will tell you that you can't because of line 3. Hence my question.
An "alternative" which I'd prefer to #HosamAly method:
private static final java.net.URL STATIC_URL = makeUrl("http://www.example.com");
public static java.net.URL makeUrl(String urlString) {
try {
return new java.net.URL(urlString);
} catch (java.net.MalformedURLException e) {
return null; //Or rethrow an unchecked exception
}
}
Use a static initializer:
public class Main {
private static final java.net.URL STATIC_URL;
static {
java.net.URL temp;
try {
temp = new java.net.URL("http://www.example.com");
} catch (java.net.MalformedURLException e) {
temp = null;
}
STATIC_URL = temp;
}
}
Note: The usage of a temporary variable is required to avoid a compilation error about assigning to the final static field twice. If the field is not final, the assignment could be done directly.
If you're sure you want to hardwire a URL. Are you sure? java.net.URL is one of the most comprehensively broken classes in the JDK. In regards to use as a "constant", there is DNS lookup involved and it uses a mutable static (albeit one guarded by a security check, if you have a SecurityManager installed).
If it's just one, a static initialiser should be fine.
private static final java.net.URL STATIC_URL;
static {
try {
STATIC_URL = new java.net.URL("http://example.com/");
} catch (java.net.MalformedException exc) {
throw new Error(exc);
}
}
(Note, you can't qualify the static field name with the class name.)
Note: You really do not want a null - throw an error of some sort and stop the class loading. I've made the constant private as it really isn't the sort of thing you want dependencies on.
If you have lots, then a method for the common code and assignment at the site of the definition is appropriate.
private static final java.net.URL STATIC_URL = constantURL("http://example.com/");
private static URL constantURL(String str) {
try {
return new java.net.URL("http://example.com/");
} catch (java.net.MalformedException exc) {
throw new Error(exc);
}
}
Again, no nulls!
The only way I got this to compile is by removing final and using the static initializer block.
/**
*
*/
package com.neurologic.example;
import java.net.MalformedURLException;
import java.net.URL;
/**
* #author The Elite Gentleman
* #since 06 December 2011
*
*/
public class StaticUrlTest {
public static URL url = null;
static {
try {
url = new URL("http://www.google.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
well, i searched the internet to this problem but didn't find any proper solution
in http://www.oodesign.com/factory-pattern.html
the author described away to register classes using reflection or object creation
i tried the object creation approach by the following code:
the factory class
package com.mf.egyptse;
import java.util.HashMap;
public abstract class ParserFactory {
private static HashMap parsers;
static
{
parsers= new HashMap();
System.out.println("This is first static block");
}
static void putParser(Object key,Object parser)
{
parsers.put(key, parser);
}
static Object getParser(Object key)
{
return parsers.get(key);
}
}
each parser register itself in the factory:
public class NormalParser extends ParserFactory implements ParsingBehavior{
/**
* Define the number of nested columns or tags to be parsed
*/
final static int NO_OF_COLOUMNS = 13;
static String input = null;
static String[] elements= {"name","sector", "p.c", "open", "close", "chgpercent", "lastprice", "high", "low","value","volume","trades","marketcap"};
static
{
ParserFactory.putParser("normal", new NormalParser());
}
and the main is :
public class Main {
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// NileParser.parseNile();
// OTCParser.parseOTC();
// NormalParser.parseNormal();
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
the interface is:
package com.mf.egyptse;
import java.io.File;
import java.io.IOException;
public interface ParsingBehavior {
void parseToXML(CharSequence input,File file) throws IOException;
}
this code return always nullpointer exception while executing. the porblem is that the static block don't executed. so what is the solution ?
As answered by "Snicolas", your problem is that the HashMap is not populated by the time its being used. Your static block in main should load all the necessary parser classes such that these classes register themselves first.
public class Main {
static {
// Load necessary parser classes
Class.forName("normal");
}
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
Getparser should return a ParsingBehavior.
Cast inside it.
But your problem comes from the fact that your parser class is not loaded by the jvm, as it is not used by your main. So static code is not executed.
Your are mixing your factory with a bus. Let the main register your parser in the factory.