I need to use the method org.junit.Assert.assertEqualsin my test script but the Assert remains red and shows as an unresolved symbol. I do installed the junit and I don't know why only the Assert remains unresolved. I'm new to java btw. Here is the screenshot of my code
Really need some help! Thank you so much!
PS: I saw there was another post about this issue and resolved by import static org.junit.Assert.*; but this doesn't work at my side.
In JUnit 5, you can import assertion methods like follows:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class UnitTest {
// we can use JUnit 5's #Test annotation
#Test
void testEquals() {
assertEquals(1, 1);
}
}
In JUnit 4, assertions use the imports as you are using: import static org.junit.Assert.assertEquals;
Add spring boot starter test maven dependency and then do static import.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
import static org.junit.jupiter.api.Assertions.*;
Related
I am very new to Apache Spark framework, trying to setup my first jUnit like follows:
package com.sample.ccspark;
import com.holdenkarau.spark.testing.SharedJavaSparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.List;
import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class SimpleTest extends SharedJavaSparkContext {
#Test
public void initializationWorks() {
List<Integer> list = asList(1, 2, 3, 4);
JavaRDD<Integer> rdd = jsc().parallelize(list);
assertThat(rdd.count(), is(list.size()));
}
}
with the following dependencies in the pom.xml
<dependency>
<groupId>com.holdenkarau</groupId>
<artifactId>spark-testing-base_2.11</artifactId>
<version>2.2.0_0.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>2.2.0</version>
</dependency>
everything happily compiles, however when running I am getting the following exception:
Exception in thread "dispatcher-event-loop-6" java.lang.NoClassDefFoundError:
scala/runtime/AbstractPartialFunction$mcVL$sp
I do not have Spark or Scala installed locally yet, was under impression that testing framework should take care of all dependencies. Is there something I am missing here?
In the artifacts names
<artifactId>spark-testing-base_2.11</artifactId>
<artifactId>spark-core_2.10</artifactId>
the last number is the version of Scala. I guess you should select only one for both cases.
I have pluged up require dependency
testCompile 'org.mockito:mockito-core:1.10.19'
Then I put my test code to /src/test/java/ directory
then I have tried launch such test
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class PresenterActivityAcceptNotAcceptTest {
#Test
public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
boolean dd = true;
assertThat(dd, is(true));
}
it works properly, but if I add anything witch associated with Mock lib
for example #RunWith
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
#RunWith(MockitoJUnitRunner.class)
public class PresenterActivityAcceptNotAcceptTest {
#Test
public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
boolean dd = true;
assertThat(dd, is(true));
}
I got such error
Error:Execution failed for task ':Application:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Error:(10, 10) error: cannot find symbol class MockitoJUnitRunner
Error:(5, 27) error: package org.mockito.runners does not exist
/home/aleksey/Downloads/NTZ/FittingRoom/Application/src/test/java/com/fittingroom/newtimezone/presenters/PresenterActivityAcceptNotAcceptTest.java
What am I doing wrong?
If I forger about something feel free to ask
Thanks in advance!
It looks like Gradle is not doing it's job.
Manually adding the jars may fixed the problem.
How to Download and Install jar go here .
and for download mockito use this link
https://mvnrepository.com/artifact/org.mockito/mockito-core/1.10.19
As stated in Baeldung's article, starting from Mockito version 2.2.20, the package for MockitoJUnitRunner has changed. So change :
import org.mockito.runners.MockitoJUnitRunner;
To :
import org.mockito.junit.MockitoJUnitRunner;
As usual, you have to import the mockito-core library in your build.gradle :
dependencies {
testImplementation 'org.mockito:mockito-core:4.2.0'
}
As a side note, you will also need to change import for Matchers if you use them. For instance :
From :
import static org.mockito.Matchers.any;
To :
import static org.mockito.Mockito.any;
Got the same issue. Attempted to implement the developer.android documentation example.
Fixed by changed org.mockito version to the recent at the time in build.gradle :
dependencies {
testImplementation 'org.mockito:mockito-core:2.28.2'
}
Open File > Project Structure...
and then add it manually as library dependency:
I also got this exception when I tried to write instrumentalTests in src/androidTest/java/ but by default mockito's scope in dependencies is set as Unit Test implementation (you can see that in File => Project Structure => Modules => Dependencies). I've just changed this parameter to Test implementation and it works!
does your project look like this?:
While starting maven with test parameters, I get the above mentioned exception. While creating the integration test deployment, I get the following:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEJB0466: Failed to process business interfaces for EJB class class ..contract.ContractMockService
The concerning class looks like this:
package ..integration.bestand.contract;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.ejb.Local;
import javax.ejb.Stateless;
import org.apache.deltaspike.core.api.exclude.Exclude;
import org.apache.deltaspike.core.api.projectstage.ProjectStage;
...
#Exclude(ifProjectStage = {
ProjectStage.Production.class,
ProjectStage.Staging.class,
..Integration.class,
..Qs.class,
..PatchQs.class
})
#Stateless
#Local(IContractIntService.class)
public class ContractMockService implements IContractIntService {
...
return ContractBuilder.build();
}
}
The interface IContractIntService looks like:
package ..integration.bestand.contract;
import javax.ejb.Local;
...
#Local
public interface IContractIntService {
public enum State {
SUCCESS,
UNKNOWN_ERROR,
NOT_FOUND;
// TODO: Stati für Fehler hier definieren
}
//Interface comment
Result<State, ContractDTO> retrieveContract(String contractIdentifier);
}
Note: The interface is in another project which is included via maven.
The Test looks like this:
package ..api.contractregistration.service;
import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.logging.Logger;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestWatcher;
import org.junit.runner.RunWith;
import ..core.test.IntegrationTest;
#RunWith(Arquillian.class)
#Category(IntegrationTest.class)
public class ContractRegistrationIntegrationTest {
protected final Logger log = Logger.getLogger(ContractRegistrationIntegrationTest.class.getCanonicalName());
#Rule
public TestWatcher watcher = new TestWatcher() {
#Override
protected void starting(org.junit.runner.Description description) {
log.info(String.format("---> Starting test: %s", description));
}
#Override
protected void failed(Throwable e, org.junit.runner.Description description) {
log.info(String.format("<--- Test failed: %s", description));
}
#Override
protected void succeeded(org.junit.runner.Description description) {
log.info(String.format("<--- Test succeeded: %s", description));
}
};
#Deployment
public static WebArchive createDeployment() {
WebArchive result = ShrinkWrap.create(WebArchive.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
.addPackages(true, "..ejb.portal")
.addPackages(true, "..core")
.deletePackages(true, "..core.config.deltaspike")
.addPackages(true, "..integration")
.addPackages(true, "..api")
.addPackages(true, "org.apache.deltaspike.core")
.addPackages(true, "..ejb.util");
System.out.println("########## TEST DEPLOYMENT########" + result.toString(true));
return result;
}
#Test
public void test() {
String tempPw = "bla"; // result.getDto();
assertThat(tempPw, any(String.class));
}
}
The remarkable thing about this test is, that I'm not even using anything of the MockService inside a test.
The maven configuration looks like this:
Goals: clean test -Parq-wildfly-managed
JRE VM Arguments: -Djboss.home="myLocalWildflyDirectory"
JAVA_HOME is set to jdk8.
Last thing is my pom, specifically the part of the container "arq-wildfly-managed":
...
<profile>
<!-- An optional Arquillian testing profile that executes tests in your WildFly instance, e.g. for build server -->
<!-- This profile will start a new WildFly instance, and execute the test, shutting it down when done -->
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id>
<dependencies>
<dependency>
<groupId>org.wildfly.arquillian</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.ivi.torino</groupId>
<artifactId>torino-integration-bestand-mock-ejb</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.ivi.torino</groupId>
<artifactId>torino-integration-docservice-mock-ejb</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.ivi.torino</groupId>
<artifactId>torino-integration-bestand-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</profile>
...
A normal maven build with clean verify package install (just no test included) builds successfully.
Note: For this post, I renamed the packages to exclude company specializations.
Similar errors suggest correcting the ShrinkWrap deployment, but I included virtually every package there is and even tried to explicitly include the interface-class. But still, the same error remains.
What could cause this?
Try this in the Test (ShrinkWrap):
.addAsResource(new StringAsset("org.apache.deltaspike.ProjectStage=IntegrationTest"), "META-INF/apache-deltaspike.properties")
And change your Exclude to this:
#Exclude(exceptIfProjectStage = ProjectStage.IntegrationTest.class)
If you need to exclude additional Stages, add them to this very exclude statement
A bit late, but a better solution to the problem was the following:
Inside the ShrinkWrap deployment, a use of the shrinkwrap maven resolver is needed. So, instead of
.addPackages(true, "org.apache.deltaspike.core")
inside the creation of result, use the maven resolver. Should look something like this:
ShrinkWrap
.create(WebArchive.class, "test.war")
.addAsLibraries(
resolver.artifact("org.apache.deltaspike.core")
.resolveAsFiles());
The artifact is the maven artifactId. this will return another .war. multiple .wars (created from the resolver or the way you see in the original question) can be merged. This merged .war then has to be returned from the deployment method.
Reason behind this:
External includes (in this case deltaspike) are missing resources once you import them via ShrinkWrap.create.*.addAsPackages.., so this should only be used for internal project packages. To use the maven resolver, you can include the following in the .pom-file:
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven</artifactId>
<scope>test</scope>
</dependency>
credits to dzone.com for the maven resolver code snippets. I'm currently working on another project, so I can't show the original code, but it was very similar to this.
Maybe this solution will help someone in the future.
I've written the simple Java script below in order to learn more about TDD, IntelliJ and Java itself.
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.both;
public class JUnit_Dummy {
private StringJoiner joiner;
private List<String> strings;
#Before
public void setUp() throws Exception {
strings = new ArrayList<String>();
joiner = new StringJoiner();
}
....
#Test
public void shouldContainBothStringsWhenListIsTwoStrings() {
strings.add("one");
strings.add("two");
assertThat(joiner.join(strings),
both(containsString("A")).
and(containsString("B")));
}
}
_____________
import java.util.List;
public class StringJoiner {
public String join(List<String> strings) {
if(strings.size() > 0) {
return (strings.get(0);
}
return "";
}
}
I'm trying to use the "containsString" method inside an assertion, but IntelliJ keeps telling me that it "cannot resolve method 'containsString(java.lang.String)". This despite the fact that the jUnit docs (http://junit.sourceforge.net/javadoc/org/junit/matchers/JUnitMatchers.html#containsString(java.lang.String)) tell me that this method does accept a String parameter.
I've tried swapping out various import statements, including the following:
import static org.hamcrest.Matcher.containsString;
import static org.hamcrest.Matcher.*;
import static org.hamcrest.CoreMatchers.*;
The best that I get is a greyed-out import statement telling me that the import statement is unused. Not sure what the problem is, any help would be appreciated.
UPDATE:
Here is the exact compiler error:
java: cannot find symbol
symbol: method containsString(java.lang.String)
location: class JUnit_Dummy
I thought I had tried every worthwhile import statement already, but this one did the trick:
import static org.junit.matchers.JUnitMatchers.*;
I faced the same issue with a Spring Boot app.
Seems like this is a dependency ordering issue.. one of the dependencies mentioned in pom.xml before the "spring-boot-starter-test" artifact was overriding the hamcrest version.
So all I did was change the order (moved this dependency up):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I'm using Spring Boot 1.5.7.RELEASE.
We are supposed to use containsString method of hamcrest library.
My suggestion would be to stick to Junit 4 and import hamcrest library 1.3 in your build path. This would do the trick.
This will allow you to access other features of hamcrest library as well.
The solution can also be found by adding the required static imports manually. Or you can configure the required static imports in favorites tab of eclipse.
try this instead
import static org.hamcrest.CoreMatchers.*;
I'm working with MAVEN - doing a tutorial and I ran into this same issue.
I used the "import static org.hamcrest.CoreMatchers.*;" solution and that failed.
So I then moved JUNIT to be first on the list in the POM file - and that solved it.
My intention is to use assertArrayEquals(int[], int[]) JUnit method described in the API for verification of one method in my class.
But Eclipse shows me the error message that it can't recognize such a method. Those two imports are in place:
import java.util.Arrays;
import junit.framework.TestCase;
Did I miss something?
This would work with JUnit 5:
import static org.junit.jupiter.api.Assertions.*;
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
This should work with JUnit 4:
import static org.junit.Assert.*;
import org.junit.Test;
public class JUnitTest {
/** Have JUnit run this test() method. */
#Test
public void test() throws Exception {
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
}
}
This is the same for the old JUnit framework (JUnit 3):
import junit.framework.TestCase;
public class JUnitTest extends TestCase {
public void test() {
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
}
}
Note the difference: no Annotations and the test class is a subclass of TestCase (which implements the static assert methods).
This could be useful if you want to use just assertEquals without depending on your Junit version
assertTrue(Arrays.equals(expected, actual));
Try to add:
import static org.junit.Assert.*;
assertArrayEquals is a static method.
If you are writing JUnit 3.x style tests which extend TestCase, then you don't need to use the Assert qualifier - TestCase extends Assert itself and so these methods are available without the qualifier.
If you use JUnit 4 annotations, avoiding the TestCase base class, then the Assert qualifier is needed, as well as the import org.junit.Assert. You can use a static import to avoid the qualifier in these cases, but these are considered poor style by some.