Below indicates the ListResourceInt.java file method.
#Test
#Transactional
public void testList() {
List<Integer> actual = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5);
assertThat(actual).isEqualTo(expected);
}
But it will generate following error.
"error: cannot find symbol" symbol: method is(List)
I am using gradle and jhipsterVersion: 4.8.2
Build.gradle dependencies as this.
How to resolve it?
Solved the problem by changing to assertThat(actual).isEqualTo(expected);
error logs as this
You can probably fix this using the following in gradle
dependencies {
testCompile 'junit:junit:4.8.2'
}
or as stated in the docs about JUnit 4.10 and before.
which could provide you the static import for is and the code shall work as follows:-
#org.junit.Test
#org.springframework.transaction.annotation.Transactional
public void testList() {
java.util.List<Integer> actual = java.util.Arrays.asList(1, 2, 3, 4, 5);
java.util.List<Integer> expected = java.util.Arrays.asList(1, 2, 3, 4, 5);
org.junit.Assert.assertThat(actual, org.hamcrest.core.Is.is(expected));
}
Note:- I've intentionally used fully qualified names to make sure they are not confused with other and these can be updated accordingly in your code.
Related
I am using Junit 3.8.1 and updated Jmokit to 1.49
I have a project in which existing tests present with MockUp. Having private methods mocked. After updating Jmockit jar to 1.49 version getting error as follows
java.lang.IllegalArgumentException: Unsupported fake for private method
My Java class to test is
public class Foo {
String aVar;
public Foo(String str) {
aVar = str;
}
private void concatStr(String append) {
aVar = aVar.concat(append);
}
public void doSomeTask() {
concatStr("Test");
}
}
and test class is
public class FooTest extends TestCase {
public FooTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(FooTest.class);
}
public void test() {
new MockUp<Foo>() {
#Mock
private void concatStr(String append) {
Assert.assertEquals("Test", append);
}
};
Foo foo = new Foo("demoString");
foo.doSomeTask();
}
}
On console getting error as below
[INFO] Running org.test.jmokitupdate.FooTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.028 s <<< FAILURE! - in
org.test.jmokitupdate.FooTest
[ERROR] test(org.test.jmokitupdate.FooTest) Time elapsed: 0.025 s <<< ERROR!
java.lang.IllegalArgumentException: Unsupported fake for private method
Foo#concatStr(Ljava/lang/String;)V found
at mockit.internal.faking.FakedClassModifier.visitMethod(FakedClassModifier.java:96)
at mockit.asm.methods.MethodReader.readMethodBody(MethodReader.java:118)
at mockit.asm.methods.MethodReader.readMethod(MethodReader.java:75)
at mockit.asm.methods.MethodReader.readMethods(MethodReader.java:62)
at mockit.asm.classes.ClassReader.readFieldsAndMethods(ClassReader.java:196)
at mockit.asm.classes.ClassReader.accept(ClassReader.java:89)
at mockit.internal.faking.FakeClassSetup.modifyRealClass(FakeClassSetup.java:80)
at mockit.internal.faking.FakeClassSetup.redefineMethods(FakeClassSetup.java:61)
at mockit.MockUp.redefineClass(MockUp.java:114)
at mockit.MockUp.<init>(MockUp.java:78)
at org.test.jmokitupdate.FooTest$1.<init>(FooTest.java:31)
at org.test.jmokitupdate.FooTest.test(FooTest.java:31)
Earlier versions of JMockit allowed mocking private methods, and honestly, I thought it was a brilliant differentiator with other mocking-frameworks. Sadly, more recent versions have eliminated the ability to mock privates - became a warning in 1.45 and an exception in 1.47.
There is no real official explanation, although supposition is that private methods should be so simple they do not need testing/mocking. By extension, if you are trying to access it for purposes of testing, then it should not be private. People (other than you) would likely want to also alter the behavior, and that your need to access it for test purposes is strongly suggesting the method ought to be accessible. Make it protected or package-private. FWIW, there are annotations like "#VisibleForTesting" that can be used to help indicate the intent.
So you know, 1.47 also removed the "Deencapsulation" mechanism which was one of my favorite tools for inspecting/setting private data. Painful at the time I had to convert, because it littered my test code, but in hind sight, #Tested/#Injectable (the replacement) is way cleaner. As the maintainer indicates, JMockit is not intended as a way to get at privates, there are other frameworks that do that and no sense in doing the job that they do better. I switched over to Apache's commons-lang3 (FieldUtils/MethodUtils/etc), but other frameworks exist
HelloWorld.ceylon
import java.util { HashMap } //Error:(1, 8) ceylon: package not found in imported modules: java.util (define a module and add module import to its module descriptor)
void run() {
print("test");
}
module.properties
module CeylonHelloWorld "1.0" {
import java.base "8";
}
I get an exception in HelloWord.ceylon file
When I try that code, I get:
Incorrect syntax: mismatched token CeylonHelloWorld expecting initial-lowercase identifier
In module.ceylon.
The name of a module is supposed to be of form foo.bar.baz (initial-lowercase identifiers separated by periods).
Like mentioned by Gavin you will have to use a legal module name, when I change your code to use the module name "java8test" I get the following output when compiling:
$ ceylon compile java8test
warning: It looks like you are using class files from a Java newer than 1.7.
Everything should work well, but if not, let us know at https://github.com/ceylon/ceylon-compiler/issues.
In the near future, the Ceylon compiler will be upgraded to handle Java 1.8.
./source/java8test/run.ceylon:1: warning: import is never used: 'HashMap'
import java.util { HashMap }
^
2 warnings
Note: Created module java8test/1.0.0
Which is all as expected.
module.ceylon
module holaCeylon "1.0.0"{
import java.base "7"; // versiĆ³n 7 JDK
}
package.ceylon
shared package holaCeylon;
Now we go back to the run.ceylon file and import the java.util.HashMap Java library.
run.ceylon
import java.util { HashMap }
shared void run(){
print("Importando librerias de Java en Ceylon");
value romanos = HashMap<String,Integer>();
romanos.put("I", 1);
romanos.put("V", 5);
romanos.put("X", 10);
romanos.put("L", 50);
romanos.put("C", 100);
romanos.put("D", 500);
romanos.put("M", 1000);
print(romanos.values());
print(romanos.keySet());
}
Output:
salida
Code:
http://codemonkeyjunior.blogspot.mx/2015/03/ceylon-interoperabilidad-con-java.html
I am converting Android 4.x code to use ActionBarSherlock so that our App can be compatible with Gingerbread.
So far so good, but it fails launching a new instance of a fragment.
My MainActivity extends SherlockFragmentActivity implements ActionBar.TabListener.
The code fails here where case is 0:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
mFragmentProjects = ProjectsFragment.newInstance(position);
return mFragmentProjects;
case 1:
mFragmentContacts = FragmentPeople.newInstance(position, 0);
return mFragmentContacts;
}
return ArrayListFragment.newInstance(position);
}
Where case is 0 it supposed to initialize the fragment but I get this exception:
ClassNotFoundException. The only other clue I have is:
"this" in PathClassLoader and in "name" it says android.app.ActionBar$TabListener
I guess this has something to do with TabListener or libraries not included / loading correctly? I have already cleaned the project.
The fragment ProjectsFragment extends SherlockListFragment.
newInstance is pretty straitforward:
static ProjectsFragment newInstance(int num) {
ProjectsFragment f = new ProjectsFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
It turns out that although MainActivity has no reference to ActivityY, the mere fact that ActivityY did not have the SherlockFragment code made it fail. To describe this differently:
MainActitivy uses ProjectsFragment which is a list
When you click on a list in ProjectsFragment it calls ListsActivity
ListsActivity references ItemsFragment
I had to change ItemsFragment to Sherlock code before MainActivity would work. It seems Java "looks ahead" in some way when you're working with pagers and tabs and fragments.
I have a JUnit 4 test which creates test data and asserts the test condition for every single data. If everything is correct, I get a green test.
If one data fails the test, the execution of the whole test is interrupted. I would like to have a single JUnit test for each data. Is it possible to spawn JUnit tests programmatically, so that I get a lot of tests in my IDE?
The reason for this approach is to get a quicker overview which test fails and to continue the remaining tests, if one data fails.
It sounds like you'd want to write a parameterized test (that does the exact same checks on different sets of data).
There's the Parameterized class for this. This example shows how it can be used:
#RunWith(Parameterized.class)
public class FibonacciTest {
#Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
}
private final int input;
private final int expected;
public FibonacciTest(final int input, final int expected) {
this.input = input;
this. expected = expected;
}
#Test
public void test() {
assertEquals(expected, Fibonacci.compute(input));
}
}
Note that the data() method returns the data to be used by the test() method. That method could take the data from anywhere (say a data file stored with your test sources).
Also, there's nothing that stops you from having more than one #Test method in this class. This provides an easy way to execute different tests on the same set of parameters.
To tell you first, i have tried and tried it again and now i need some help
Heres my code
package staticPkg;
public class Static {
public static final String staticMethod() {
System.out.println("Static method called");
return "Static called";
}
}
package staticPkg;
public class TargetClass {
Static staticClass;
public String callHere() {
return Static.staticMethod();
}
}
package staticPkg;
import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
#PrepareForTest({Static.class})
public class TestClass {
Static staticClass = null;
#ObjectFactory
public IObjectFactory getObjectFactory() {
System.out.println("got object factory");
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
#BeforeMethod
public void setup() {
System.out.println("print me");
PowerMock.mockStatic(Static.class);
staticClass = PowerMock.createMock(Static.class);
}
#Test
public void testMe() {
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}
}
And heres the log
[Parser] Running:
C:\MockWorkspace\Mock\temp-testng-customsuite.xml
got object factory
print me
Static method called
FAILED: testMe
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:521)
at org.easymock.EasyMock.expect(EasyMock.java:499)
at staticPkg.TestClass.testMe(TestClass.java:46)
... Removed 22 stack frames
===============================================
staticPkg.TestClass
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Mock
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Help please, i have tried a variety of solutions, can't get it done.
Please can anyone try this code and correct it for success?
I get error in EasyMock.expect ...............
Got a work around at http://blogs.bytecode.com.au/glen/2006/10/12/doing-bytecode-kungfu-with-javassist.html
And it works
But wait..........I am stuck again
My testcase works fine when runs alone, but when run with Ant, it gives problem. Might be other test cases of different files are interfering.
I got the same error, when my individual test case was using #PrepareTest & easymock/powermock
[testng] ====================STATIC CALLED===========================
[testng] javassist.CannotCompileException: by java.lang.LinkageError: loader (instance of sun/misc/Launcher$AppClass
Loader): attempted duplicate class definition for name: "com/symantec/mobius/aggregator/submission/SubmissionFactory"
[testng] at javassist.ClassPool.toClass(ClassPool.java:1085)
[testng] at javassist.ClassPool.toClass(ClassPool.java:1028)
[testng] at javassist.ClassPool.toClass(ClassPool.java:986)
[testng] at javassist.CtClass.toClass(CtClass.java:1110)
Try extending from PowerMockTestCase. The TestNG support will also be updated in next version of PowerMock (1.4.9).
I faced this same issue, and struggled a lot. Finally, found the following solution:
Another alternative is to set the object-factory to org.powermock.modules.testng.PowerMockObjectFactory in the TestNG suite.xml. Here is a sample suite file:
<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
<test name="dgf">
<classes>
<class name="com.example.ClientTest"/>
</classes>
</test>
</suite>
Of course, you can also extend your test case from PowerMockTestCase as told by Johan.
Mock all the static methods in static class before proceeding to mock the static method. Try with this:
#Test
public void testMe() {
PowerMock.mockStatic(Static.class);
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}