Hot questions for Using Mockito in intellij idea

Top 10 Java Open Source / Mockito / intellij idea

Question:

IntelliJ Idea is giving following warning for one of the statements in my test cases.

Warning: Unchecked generics array creation for varargs parameter

Signals places where an unchecked warning is issued by the compiler

All I am doing is :

when(someService.someMethod(id)).thenThrow(AccountNotFoundException.class)


Answer:

A better way to accomplish that would probably be:

when(someService.someMethod(id)).thenThrow(new AccountNotFoundException());

then the compiler should infer the type correctly.

If someService.someMethod(id) has return type void you can do:

doThrow(new AccountNotFoundException()).when(someService).someMethod(id);

Please refer to the official Mockito documentation for examples like this using thenThrow. The documentation is very clear on this point.

You can also check the following StackOverflow question which is very similar (if not an exact duplicate):

How to mock and assert a thrown exception

Question:

I am using IntelliJ idea for writing simple unit test cases using JUnit and Mockito. I am using Maven for dependency management.

IntelliJ idea keeps complaining that following imports cannot be resolved:

import org.junit.Test; //Cannot resolve symbol 'Test'

import static org.mockito.Mockito.*; //Cannot resolve symbol 'mockito'

Following is the dependencies section of my project:

<dependencies>
    <!-- Dependency for JUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <!--<scope>test</scope>-->
    </dependency>
    <!-- Dependency for Mockito -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.10.19</version>
        <!--<scope>test</scope>-->
    </dependency>
</dependencies>

Following is my project structure:


Answer:

Try View -> Tool Windows -> Maven projects, then click the blue icon in the top left of the tool window (Reimport all Maven projects). You should be able to find the dependencies in the project view, under external libraries.

If this does not work, there is probably something wrong with your maven config (pom.xml). Try mvn clean install from the command line see if it gives any errors.

Question:

I have a basic java project and I want to run tests using Mockito (since I use it at work and it's easy). So I referred to this link and added the following to my build.gradle

dependencies {
    testCompile 'junit:junit:4.11'
    testCompile "org.mockito:mockito-core:1.+"
}

Even though I think mavenCentral() should be enough, I went ahead and added these to my repositories list

repositories {
    mavenLocal()
    jcenter()
    mavenCentral()
}

The ./gradlew clean build runs perfectly fine, but when I try to add the import for Mockito it doesn't get it. And my External Libraries folder in the project doesn't have the Mockito jar. I even tried using mavenLocal() in the hope that it'll pick it up from my local .m2 directory, but it doesn't. I've been looking around and trying out all combinations for 2 hours now with absolutely no result. I don't want to add the jar to the project. I want to let gradle pull it from the central repo and compile it.

Thanks for any help in advance.


Answer:

I found the answer here Apparently clicking on that refresh button refreshes the dependencies. Else right click on module -> Open Module settings -> Go to Dependencies tab and add your dependency either from your local m2 folder or provide the maven central URL for the dependency. I was too used to Eclipse doing stuff for me I guess. :)

Question:

I am using Intellij, and my external dependencies folder show I am using mockito-all-1.10.19.jar.

I am using this simple Mockito example.

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class AuditUnitTests {

    @Mock
    AuditTwo two;

    @InjectMocks
    AuditOne one;

    @Test
    public void test1() {
        one.sayHelloFilter("Saurav");
        one.sayHelloFilter("Dravid");
        one.sayHelloFilter("Sachin");
        verify(two, times(2)).sayHello();
    }
}

However my Intellij complains that It cannot resolve Mock and InjectMocks annotations. How can I resolve it ?

Note: I am using Ivy for dependency management:

   <dependency org="junit" name="junit" rev="4.12" conf="test"/>
    <dependency org="org.mockito" name="mockito-all" rev="1.10.19" conf="test"/>

Answer:

Your static import is not sufficent. You have to add following additional imports.

import org.mockito.InjectMocks;
import org.mockito.Mock;

Question:

So I'm trying to create a live template in Intellij for Mockito. What I have is follows:

$VAR$ = Mockito.mock($VARCLASSNAME$);$END$

VAR has the expression of suggesteFirstVariableName()

Now what do I need to put in for the expression so that it automatically picks up the class name of the VAR?

Thanks,


Answer:

This is what I have:

$CLASSNAME$ $VAR$ = Mockito.mock($CLASSNAME$.class);$END$

Expressions

 - CLASSNAME:
 - VAR: decapitalize(CLASSNAME)

So, I just need to type the name of the class I want to mock once, and all the rest is automatically completed.

Hope it helps.

Question:

In my project Mockito.times(1) is often used when verifying mocks:

verify(mock, times(1)).call();

This is redundant since Mockito uses implicit times(1) for verify(Object), thus the following code does exactly what the code above does:

verify(mock).call();

So I'm going to write an a structural search drive inspection to report such cases (let's say, named something like Mockito.times(1) is redundant). As I'm not an expert in IntelliJ IDEA structural search, my first attempt was:

Mockito.times(1)

Obviously, this is not a good seach template because it ignores the call-site. Let's say, I find it useful for the following code and I would not like the inspection to trigger:

VerificationMode times = Mockito.times(1);
                      // ^ unwanted "Mockito.times(1) is redundant"

So now I would like to define the context where I would like the inspection to trigger. Now the inspection search template becomes:

Mockito.verify($mock$, Mockito.times(1))

Great! Now code like verify(mock, times(1)).call() is reported fine (if times was statically imported from org.mockito.Mockito). But there is also one thing. Mockito.times actually comes from its VerificationModeFactory class where such verification modes are grouped, so the following line is ignored by the inspection:

verify(mockSupplier, VerificationModeFactory.times(1)).get();

My another attempt to fix this one was something like:

Mockito.verify($mock$, $times$(1))

where:

  • $mock$ is still a default template variable;
  • $times$ is a variable with Text/regexp set to times, Whole words only and Value is read are set to true, and Expression type (regexp) is set to (Times|VerificationMode) -- at least this is the way I believed it should work.

Can't make it work. Why is Times also included to the regexp? This is the real implementation of *.times(int), so, ideally, the following line should be reported too:

verify(mockSupplier, new Times(1)).get();

Of course, I could create all three inspection templates, but is it possible to create such a template using single search template and what am I missing when configuring the $times$ variable?

(I'm using IntelliJ IDEA Community Edition 2016.1.1)


Answer:

Try the following search query: Mockito.verify($mock$, $Qualifier$.times(1))

With $Qualifier$ text/regexp VerificationModeFactory|Mockito and occurrences count 0,1 (to find it when statically imported also).

To also match new Times(1) you can use the following query: Mockito.verify($mock$, $times$)

With $times$ text/regexp .*times\s*\(\s*1\s*\) and uncheck the Case sensitive checkbox.

Question:

I am relatively new to using Java and would like to improve these unit tests I have written by using mocks. I have heard mockito is a good library so I am trying to declare the dependency in the pom.xml file of my project but wherever I place the lines in the file, I am given an error 'Invalid content was found starting with the element 'dependency'. I have looked on the Mockito docs but they seem to jump straight in to importing at the top of your test files not actually configuring it.

My pom.xml file currently:

<modelVersion>4.0.0</modelVersion>


<groupId>groupId</groupId>
<artifactId>JAirport</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.10</source>
                <target>1.10</target>
            </configuration>
        </plugin>

    </plugins>
</build>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.8.4</version>
    <scope>test</scope>
</dependency>
</project>

Thank you!


Answer:

You need to wrap your <dependency> tag in a <dependencies> tag

<modelVersion>4.0.0</modelVersion>


<groupId>groupId</groupId>
<artifactId>JAirport</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.10</source>
                <target>1.10</target>
            </configuration>
        </plugin>

    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.8.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>

Question:

I wanted to learn a bit about Mockito, but when I run my test class I get the following errors, even though I import the package:

What do I have to do, to make the code work?


Answer:

put this in your build.gradle file:

dependencies {
...
    testCompile 'org.mockito:mockito-core'
}

note: the build.gradle file must be located in the application root, ie: FantasticFeastsTemplate/.

Hope that helps!