Mock assertEquals not found - eclipse

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

Related

unit test failing if Log Member object (#Slf4j isn't found groovy.lang.MissingPropertyException: No such property: log for class:

I'm helping my development team with some logging code in our framework.
using spring AOP I've created a groovy class called LoggingAspect. Its main purpose is to log method execution times for classes in com.zions.comon.services.logging directories and
annotated with #Loggable.
Since some classes already have #sl4j logging I need to detect if hat log member objects exists and use the built in #slf4j logging for that class. If it doesn't I need to execute the #sl4j annotation in aspect logging code.
The first statement in the try block will check if log member exists on object. If it does, then iLog will get set to incoming object's logger. However I'm not sure how to complete the rest of the code Once I detect the log member object. I don't expect anyone to write this code for me but would appreciate any suggestions/areas of researcoh on how to do this - such as using "if"
The logic should go something like:
Intercept and calculate method logging times in select classes
Check for existing log member object that indicates #slf4j is already present in class
If log member object exits use #sl4j logging features already built into that class
If log member object doesnt exist use #slf4j logging in logging Aspect code.
any help would be appreciated
"logging flow diagram"
Reverted code to original version - My LoggingAspect code looks like this at the moment
package com.zions.common.services.logging
import groovy.util.logging.Slf4j
import org.slf4j.Logger
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.EnableAspectJAutoProxy
#Aspect
#Configuration
#Slf4j
#EnableAspectJAutoProxy(proxyTargetClass=true)
public class LoggingAspect {
*
* This is a Logging Aspect for the Loggable annotation that calculates method runtimes
* for all methods under classes annotated with #Loggable*/
/**
* Logs execution time of method under aspect.
*
* #param joinPoint - method under join
* #return actual return of method under join point.
* #throws Throwable
*/
#Around('execution (* *(..)) && !execution(* *.getMetaClass()) && #within(com.zions.common.services.logging.Loggable)')
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
def obj = joinPoint.this
Logger iLog = log
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
try {
/*First statement of try block attempts to test if log members exist on object.
If it does, then iLog will get set to incoming object's logger*/
obj.log.isInfoEnabled()
iLog = obj.log
} catch (e) {}
iLog.info("${joinPoint.getSignature()} executed in ${executionTime}ms");
return proceed;
}
}
If its helpful my logging Annotation is
package com.zions.common.services.logging
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/* Logging annotation to be used at class level
* Loggable annotation for all methods of a class annotated with the #Loggable annotation*/
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface Loggable {}
I've added a junit test class that validates when log member is found - The line 'iLog = obj.log' get's called from the LoggingAspect code and the test is PASSING.
LoggingAspectSpecification.groovy
package com.zions.common.services.logging
import static org.junit.Assert.*
import groovy.util.logging.Slf4j
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Profile
import org.springframework.context.annotation.PropertySource
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification
#ContextConfiguration(classes=[LoggingAspectSpecificationConfig])
class LoggingAspectSpecification extends Specification {
#Autowired
SomeClass someClass
def 'Main flow for timing log'() {
setup: 'class to be logged'
when: 'execute something with class testing log'
someClass.methodOne()
someClass.methodTwo()
then: 'validate something logged'
true
}
}
#TestConfiguration
#Profile("test")
#ComponentScan(["com.zions.common.services.logging"])
#PropertySource("classpath:test.properties")
class LoggingAspectSpecificationConfig {
#Bean
SomeClass someClass() {
return new SomeClass()
}
}
#Loggable
#Slf4j
class SomeClass {
def methodOne() {
log.info('run methodOne')
}
def methodTwo() {
log.info('run methodTwo')
}
}
However my unit test is failing with classes that do not have #Slf4j meaning it will execute with the logger of the aspect instead of the pointcut object. The full error trace is:
groovy.lang.MissingPropertyException: No such property: log for class: com.zions.common.services.logging.SomeClass2
at com.zions.common.services.logging.SomeClass2.methodOne(LoggingAspectSpecification2.groovy:55)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89)
at com.zions.common.services.logging.LoggingAspect.logExecutionTime(LoggingAspect.groovy:42)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:643)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:632)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:174)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at com.zions.common.services.logging.LoggingAspectSpecification2.Main flow for timing log(LoggingAspectSpecification2.groovy:27)
The second unit test code is below - (the only difference is that #Slf4j) is not present in the classes.
LoggingAspectSpecification2.groovy
package com.zions.common.services.logging
import static org.junit.Assert.*
import groovy.util.logging.Log
import groovy.util.logging.Slf4j
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Profile
import org.springframework.context.annotation.PropertySource
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification
#ContextConfiguration(classes=[LoggingAspectSpecificationConfig2])
class LoggingAspectSpecification2 extends Specification {
#Autowired
SomeClass2 someClass2
def 'Main flow for timing log'() {
setup: 'class to be logged'
when: 'execute something with class testing log'
someClass2.methodOne()
someClass2.methodTwo()
then: 'validate something logged'
true
}
}
<!-- language: lang-groovy -->
#TestConfiguration
#Profile("test")
#ComponentScan(["com.zions.common.services.logging"])
#PropertySource("classpath:test.properties")
class LoggingAspectSpecificationConfig2 {
#Bean
SomeClass2 someClass2() {
return new SomeClass2()
}
}
<!-- language: lang-groovy -->
#Loggable
class SomeClass2 {
def methodOne() {
int x=10, y=20;
System.out.println(x+y+" testing the aspect logging code");
}
def methodTwo() {
int x=10, y=20;
System.out.println(x+y+" testing the aspect logging code");
}
}
I'm guessing something's wrong in my LoggingAspect code in the Try Catch block?
To resolve the error and get my unit test to pass without #Slf4j or #Log - I had to add a println statement to the SomeClass2 code as in,
int x=10, y=20;
System.out.println(x+y+" testing the apsect logging code");
adding #Log just gave it another built in log member similar to #Slf4j - adding the println statement and removing the #Log annotation force the LoggingAspect code to execute. Unit test is passing.

Junit test Failed not finding AssertArrayEquals Method in Assert class

I am using Junit 4.1. When I tried to use AssertArrayEquals(...) it's not finding that method. I tried importing everything by import static org.junit.Assert.*;. I searched in the jar file but I didn't find this method, and need suggestions to resolve this.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
public class ArraysCompareTest {
#Test
public void testArraySort() {
int [] actual= {8,7,6,5};
int [] expected= {5,6,7,8};
Arrays.sort(actual);
//it fails because it checks object references not content
assertArrayEquals(expected, actual);
}
}
The problem here is Assert class is not showing AssertArrayEquals in suggestion.
Are you sure you have the JUnit4 jar? Assert.AssertArrayEquals wasn't present in JUnit3 and before.

citrus waitFor().condition() statement not waiting when used with ftpServer

I'm trying to use the citrus-framework to test an integration that writes some files on a FTP server.
I need to wait until some file is uploaded to the ftp (I'm using waitFor().condition() statement to accomplish that) and then receive the messages sent and do some assertions.
import com.consol.citrus.annotations.CitrusTest;
import com.consol.citrus.condition.Condition;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;
import com.consol.citrus.ftp.server.FtpServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.testng.annotations.Test;
import java.io.File;
#ActiveProfiles(value = "ftpTest")
#Test
public class FtpTest extends TestNGCitrusTestDesigner {
#Autowired
FtpServer ftpServer;
#Autowired
TestContext context;
#CitrusTest(name = "ftpTest")
public void ftpTest() {
// here I start my integration that uses a cron to upload the file
// this code is irrelevant for the example
Condition waitUntilFileIsUploaded = new Condition() {
#Override
public String getName () {
return "Check files on FTP";
}
#Override
public boolean isSatisfied (TestContext testContext){
return new File("/tmp/foo_dir").listFiles().length != 0;
}
#Override
public String getSuccessMessage (TestContext testContext){
return "Files found in FTP!";
}
#Override
public String getErrorMessage (TestContext testContext){
return "No file was found in FTP";
}
};
waitFor().condition(waitUntilFileIsUploaded).seconds(120L).interval(500L);
ftpServer.createConsumer().receive(context);
}
}
When I try to run this test looks like the waitFor() is never executed and ftpServer.createConsumer().receive(context); is executed before any file could be uploaded to the FTP.
This is the error that I'm getting:
ftpTest>TestNGCitrusTest.run:57->TestNGCitrusTest.run:111->TestNGCitrusTestDesigner.invokeTestMethod:73->TestNGCitrusTest.invokeTestMethod:133->ftpTest:49 ยป ActionTimeout
Any idea how I could fix this?
Also any complete example for using FTP Java DSL with Citrus would be more than welcome!
Please use test designer receive method instead of creating the consumer on your own.
receive(ftpServer)
.header("some-header", "some-value")
.payload("some payload");
Only then test designer can arrange the test actions in proper order. This is because test designer constructs the complete test action logic first and execution takes place at the very end of the test method.
As an alternative to that you could also use test runner instead of test designer. The runner will execute each test action immediately giving you the opportunity to add custom statements as you did before.

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.

How to understand AssertThat (JUnit)?

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/