Why is my import of the containsString method not working? - java

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.

Related

Intellij can't import static org.junit.Assert.assertthat

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.*;

ConstraintCollectors not recognized in Spring Boot (STS)

I'm trying to make use of the Optaplanner constraintprovider, which works fine until I want to use the count() ConstraintCollector.
I try to use it in a groupBy-clause, but I get the error: The method count() is undefined for the type hamxConstraintProvider
I was under the assumption this should "just work"? Or should I write my own method for count? I couldn't find that happening in the examples, but seem unable to fix it either. Am I overlooking an import?
import org.optaplanner.core.api.score.stream.Constraint;
import org.optaplanner.core.api.score.stream.ConstraintFactory;
import org.optaplanner.core.api.score.stream.ConstraintProvider;
import org.optaplanner.core.api.score.stream.uni.UniConstraintCollector;
import org.optaplanner.core.api.score.stream.bi.BiConstraintCollector;
import org.optaplanner.core.api.score.stream.ConstraintCollectors.*;
import org.optaplanner.core.api.score.stream.Joiners.*;
...
public class hamxConstraintProvider implements ConstraintProvider{
#Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
skillUnavailable(constraintFactory),
balancedJobs(constraintFactory)
};
}
...
private Constraint balancedJobs(ConstraintFactory factory) {
return factory.from(Job.class)
.groupBy(Job::getEmployee,count())
.penalize("unbalancedEmployeeUsage", HardSoftScore.ONE_SOFT,count);
}
Instead of
import org.optaplanner.core.api.score.stream.ConstraintCollectors.*;
import org.optaplanner.core.api.score.stream.Joiners.*;
use static imports:
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.*;
import static org.optaplanner.core.api.score.stream.Joiners.*;
The former imports classes, the latter imports static methods.
count() and countLong() are methods of ConstraintCollectors. If it compiles but doesn't run, you're likely not providing Spring's ClassLoader to the SolverConfig.
In the next release, 7.32, we're releasing optaplanner-spring-boot-starter, which will make Spring Boot integration a lot easier (it just auto injects a SolverManager (or SolverFactory, but the former is the latter on steriods)

Why Are These Imports Errored?

As part of my uni project, I have had to clone a group member's code and work on it myself. But on the imports included below, they are underlined and I can't seem to know why or how to address this. Netbeans says that these are 'Unused imports'. I've already tried to Google this but with no luck.
What does this mean and how do I fix it? Please bear with me as I am completely new to programming and it's concepts. Thank you.
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import static org.apache.http.HttpHeaders.USER_AGENT;
As the name implies, "Unused import" is a message from the IDE (not directly related to Java) and means that you're not using that class/interface/whatever it is. Also, note that this is a warning, not an error. This means, your code can compile and execute without issues.
To fix this, just remove the unused import statements.
Example of how to raise unused import:
package something;
//this interface is never used in this class
import java.util.List;
public class Example {
public static void main(String args[]) {
System.out.println("Hello world");
}
}
Example of how to fix it:
package something;
//removed import java.util.List; since it's not used
public class Example {
public static void main(String args[]) {
System.out.println("Hello world");
}
}

Why do I get an error "package org.mockito.runners does not exist"?

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?:

Import for mockito

I am trying to put statement like
when(myDao.fetchTree(anyLong())).thenReturn(myTreeList);
and I have import
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.thenReturn; //not importing
import for thenReturn is not mapping. Is this a version issue? I am using Mockito 1.8.4.
Mockito's when returns an object of class OngoingStubbing. This class has a method thenReturn(), and that's what gets called in your example code. No additional import is needed.
when(myDao.fetchTree(anyLong())).thenReturn(myTreeList);
could be broken up as
OngoingStubbing thing = when(myDao.fetchTree(anyLong()));
thing.thenReturn(myTreeList);
You are just calling the thenReturn method of OngoingStubbing.
It should be enough if you use:
import static org.mockito.Mockito.*;
And remove the rest.
Your question: Is this a version issue?
I'd say NO, that is not a version issue.
As suggested previously, you should
create minimal test with this code in test
when(myDao.fetchTree(anyLong())).thenReturn(myTreeList);
run this code from command-line (not inside in STS or any IDE or something a like)
Q: Why run it from command-line and avoid using IDE-s etc?
A: Because sometimes code parsers and checkers and validators of your favorited IDE reports false positives about some corner-cases in code.

Categories