How to mock for custom Event? - java

MyEvent extends EventObject.
public class MyEvent extends EventObject {
private int buttonName;
public void setNum( int num) {
this.num= num;
}
public int getNum(){
return num;
}
public MyEvent(Object source) {
super(source);
}
}
With mockito-all-2.0.2-beta, I do mock the above Event for a unit test
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
public class MyEventTest {
public MyEventTest() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
/**
* Test of getButtonNum method, of class MyEvent.
*/
#Test
public void testGetButtonNumEqual() {
System.out.println("setButtonNum");
MyEvent evt = mock(MyEvent.class);
int buttonNum = 1;
evt.setButtonNum(buttonNum);
int result = evt.getButtonNum();
System.out.println(buttonNum);
System.out.println(result);
assertEquals(buttonNum, result);
}
/**
* Test of getButtonNum method, of class MyEvent.
*/
#Test
public void testGetButtonNumNotEqual() {
System.out.println("setButtonNum");
MyEvent evt = mock(MyEvent.class);
int buttonNum = 2;
int notEqualNum = 1;
evt.setButtonNum(buttonNum);
int result = evt.getButtonNum();
System.out.println(buttonNum);
System.out.println(result);
assertNotEquals(notEqualNum, result);
}
}
First Test is failed and Second Test is passed. The print output is below.
{
setButtonNum
1
0
and
setButtonNum
2
0
}
I would like to know why the first test is fail and how to do unit test a custom event.
Please, let me know what mistake I did. I appreciate your help. Thanks.

Related

No tests found matching Method addtest

I am learning Junit Testing, and I decided to make a simple calculator and test it. I created Calculation_JUnit and Calculation_JUnit_Test
Also i have a problem of using class methodsenter image description here
package com.example;
public class Calculation_JUnit {
public static int add(int a, int b){
return a+b;
}
public static int sub(int a, int b){
return a-b;
}
public static int mul(int a, int b){
return a*b;
}
public static int div(int a, int b){
return a/b;
}
}
Calculation_JUnit_Test
import org.junit.*;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.*;
import com.example.Calculation_JUnit;
public class Calculation_JUnitTest {
#Before
public void setUp() {
System.out.println("Test is passedd ");
}
#Test
public void Add_Test ()
{
Calculation_JUnit calculation_jUnit = new Calculation_JUnit();
Assert.assertEquals("Good",5, calculation_jUnit.add(2,1));
}
#Test
public void Sub_Test ()
{
Calculation_JUnit calculation_jUnit = new Calculation_JUnit();
Assert.assertEquals("Not Good",5, calculation_jUnit.add(5,1));
}
#Test
public void Mult_Test ()
{
Calculation_JUnit calculation_jUnit = new Calculation_JUnit();
Assert.assertEquals("Not Good",3, calculation_jUnit.add(5,1));
}
#Test
public void Div_Test ()
{
Calculation_JUnit calculation_jUnit = new Calculation_JUnit();
Assert.assertEquals("Not Good",5, calculation_jUnit.add(4,1));
}
}

Parameterized junit test of custom validation in springboot

I have this validator in springboot which gives error when an integer is not between 1 and 3 and i am using addConstraintViolation to print a message from properties file
public class SizeValidator implements ConstraintValidator<SizeValidation, Integer> {
private int maxSize = 500;
private int minSize = 1;
#Override
public void initialize(SizeValidation constraintAnnotation) {
maxSize = constraintAnnotation.mxSize();
minSize = constraintAnnotation.minSize();
}
#Override
public boolean isValid(Integer givenSize, ConstraintValidatorContext context) {
if (givenSize > maxSize || givenSize<= minPageSize) {
addConstraintViolation(givenSize, "{Size.wrongSize.message}", context);
return false;
}
return true;
}
private void addConstraintViolation(Integer givenSize, String errorMessage, ConstraintValidatorContext context) {
final HibernateConstraintValidatorContext customContext = context.unwrap(HibernateConstraintValidatorContext.class);
customContext.addExpressionVariable("givenSize", givenSize);
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(errorMessage)
.addConstraintViolation();
}
}
and in my validation.properties
Size.wrongSize.message=Value of size ${givenSize} should be between 1
and 3
i wanted to write a Parameterized junit test for it as following but it returns nullpointerexception where am i doing wrong please?
java.lang.NullPointerException
at sizeValidator.addConstraintViolation(SizeValidator.java:33)
intellij says its at position
context.buildConstraintViolationWithTemplate(errorMessage)
.addConstraintViolation();
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
#RunWith(Enclosed.class)
public class SizeValidatorTest{
#RunWith(Parameterized.class)
public static class TestValidEntries {
private SizeValidator validator = new SizeValidator();
private Integer val;
public TestValidEntries(Integer val) {
super();
this.val = val;
}
#Test
public void test() {
assertTrue(isValid(val));
}
#Parameterized.Parameters(name = "{index} Valid: {0}")
public static Collection data() {
return Arrays.asList(
-1, 501
);
}
public boolean isValid(Integer value) {
final HibernateConstraintValidatorContext context = mock(HibernateConstraintValidatorContext.class);
when(context.unwrap(HibernateConstraintValidatorContext.class)).thenReturn(context);
when(context.addExpressionVariable(eq("nonUnique"), anyString())).thenReturn(context);
when(context.getDefaultConstraintMessageTemplate()).thenReturn("template");
final ConstraintValidatorContext.ConstraintViolationBuilder builder = mock(ConstraintValidatorContext.ConstraintViolationBuilder.class);
when(context.buildConstraintViolationWithTemplate("template")).thenReturn(builder);
when(builder.addPropertyNode(anyString())).thenReturn(mock(ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext.class));
return validator.isValid(value, context);
}
}
}
The problem is in the configuration of the context mock.
Your configuration says:
when(context
.buildConstraintViolationWithTemplate(
"template"))
.thenReturn(builder);
But the string you pass in your code under test is: "{Size.wrongSize.message}"
Because this string do not match the mock returns null.
A better approach is to always use unspecific matchers like anyString() in the arrange part of the test method (or in setup) an specific matchers (or values) only in conjunction with Mockito.verify() in the assert part of the test method.

how to resolve NullPointerException in Junit for NeticaJ?

//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

junit error: initiallization error: coused an error: no rannable method

I am having this error while all my methods in this test are successful - all of them return true. Also tried to make boolean for each method call and use only one call for assertTrue(a && b && c && d && e).
I run the junit test in java - netbeans.
My junit code (first time using junit) is:
package redis_fast_algo;
import data_sets.FastSortAlgoData;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class FastSortAlgoStudyTest {
private DataMaker dataMake;
private final static boolean BEFORE_DELETE = false;
public FastSortAlgoStudyTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
dataMake = new DataMaker();
}
#After
public void tearDown() {
}
/**
* Test of study method, of class FastSortAlgoStudy.
*/
#Test
public void testStudy() throws Exception {
System.out.println("study");
FastSortAlgoData data = dataMake.getData(5);
FastSortAlgoStudy instance = new FastSortAlgoStudy(data);
FastSortAlgoTest testStudy = new FastSortAlgoTest(data);
testStudy.prepareForTest();
instance.study();
assertTrue(testStudy.testCheckFolderStudyCounter(BEFORE_DELETE));
assertTrue(testStudy.testCheckBodyPart(BEFORE_DELETE));
assertTrue(testStudy.testCheckTitlePart(BEFORE_DELETE));
assertTrue(testStudy.testCheckFoldersHistoryWithData(BEFORE_DELETE));
assertTrue(testStudy.testRemoveFolderHistory());
}
}

Mock Object and Interface

I'm a newbie in Unit Test with Mock Object. I use EasyMock. I try to understand this example:
import java.io.IOException;
public interface ExchangeRate {
double getRate(String inputCurrency, String outputCurrency) throws IOException;
}
import java.io.IOException;
public class Currency {
private String units;
private long amount;
private int cents;
public Currency(double amount, String code) {
this.units = code;
setAmount(amount);
}
private void setAmount(double amount) {
this.amount = new Double(amount).longValue();
this.cents = (int) ((amount * 100.0) % 100);
}
public Currency toEuros(ExchangeRate converter) {
if ("EUR".equals(units)) return this;
else {
double input = amount + cents/100.0;
double rate;
try {
rate = converter.getRate(units, "EUR");
double output = input * rate;
return new Currency(output, "EUR");
} catch (IOException ex) {
return null;
}
}
}
public boolean equals(Object o) {
if (o instanceof Currency) {
Currency other = (Currency) o;
return this.units.equals(other.units)
&& this.amount == other.amount
&& this.cents == other.cents;
}
return false;
}
public String toString() {
return amount + "." + Math.abs(cents) + " " + units;
}
}
import junit.framework.TestCase;
import org.easymock.EasyMock;
import java.io.IOException;
public class CurrencyTest extends TestCase {
public void testToEuros() throws IOException {
Currency testObject = new Currency(2.50, "USD");
Currency expected = new Currency(3.75, "EUR");
ExchangeRate mock = EasyMock.createMock(ExchangeRate.class);
EasyMock.expect(mock.getRate("USD", "EUR")).andReturn(1.5);
EasyMock.replay(mock);
Currency actual = testObject.toEuros(mock);
assertEquals(expected, actual);
}
}
So, i wonder how to Currency use ExchangeRate in toEuros(..) method.
rate = converter.getRate(units, "EUR");
The behavior of getRate(..) method is not specified because ExchangeRate is an interface.
/********************************************************************************/
So I try do myself example. Following is my codes:
/**
*Interface to access data
*/
public interface Dao {
public boolean getEntityById(int id) throws SQLException;
}
/**
*Business class do something in business layer
*/
public class Bussiness {
private Dao dao;
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
public boolean doSomeThing(int id) throws SQLException {
if(dao.getEntityById(id)) {
return true;
} else {
return false;
}
}
public static void main(String[] args) throws SQLException {
Bussiness b = new Bussiness();
b.doSomeThing(3);
}
}
package tunl;
import java.sql.SQLException;
import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* This is my unit Test
*/
#Test
public class MyUnitTest {
private Bussiness bussiness;
private Dao mock;
#BeforeTest
public void setUp() {
bussiness = new Bussiness();
mock = EasyMock.createMock(Dao.class);// interface not class
bussiness.setDao(mock);
}
public void testDoSomeThing() throws SQLException {
EasyMock.expect(mock.getEntityById(3)).andReturn(true);
EasyMock.replay(mock);
Assert.assertTrue(bussiness.doSomeThing(3));
}
}
So, The unit Tess run correctly
But when i want to run main method in Business Object:
public static void main(String[] args) throws SQLException {
Bussiness b = new Bussiness();
b.doSomeThing(3);
}
I have to add the constructor for Business.
public Bussiness() {
dao = new DaoImpl();
}
So, my business class is:
package tunl;
import java.sql.SQLException;
public class Bussiness {
private Dao dao;
public Bussiness() {
dao = new DaoImpl();
}
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
public boolean doSomeThing(int id) throws SQLException {
if(dao.getEntityById(id)) {
return true;
} else {
return false;
}
}
public static void main(String[] args) throws SQLException {
Bussiness b = new Bussiness();
b.doSomeThing(3);
}
}
Also I have to implement Dao interface:
package tunl;
import java.sql.SQLException;
public class DaoImpl implements Dao {
#Override
public boolean getEntityById(int id) throws SQLException {
if(id == 3) {
System.out.println("System input 3 ");
return true;
}
System.out.println("You have to input 3 ");
return false;
}
}
In design, you always create interface for all of the classes which will be tested (like DaoImpl) !!!
So is it correct?
EasyMock creates a mock object based on the interface. The mock object implements all the methods of the interface and for those methods you specify (e.g. with expect), it "replays" the specified behaviour when they are called.
When a mock object is created, it is in recording mode. The line
EasyMock.expect(mock.getRate("USD", "EUR")).andReturn(1.5);
specifies that when mock.getRate is called with the given parameters, it shall return 1.5 . Then the object is put into replay mode with the call
EasyMock.replay(mock);
All this is explained in more details in the documentation.
Update: to your comment - Currency is passed an instance of ExchangeRate here:
public Currency toEuros(ExchangeRate converter) { ... }
All it cares is that it gets an object implementing that interface, so that
rate = converter.getRate(units, "EUR");
can be called. The test method, then, passes the mock object it created to the currency object:
Currency actual = testObject.toEuros(mock);
Hope this helps; if not, maybe you could read some introductory text on OOP, interfaces and inheritance to get a better understanding.
In the code example in your answer, the Dao object should be passed to Bussiness rather than created internally, since the latter effectively prevents unit testing.
public static void main(String[] args) throws SQLException {
Bussiness b = new Bussiness();
b.setDao(new DaoImpl());
b.doSomeThing(3);
}
You could also add a parameterized constructor to Bussiness to make the initialization in one step instead of two.

Categories