Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot resolve method "when"

Tags:

mockito

I'm following the Vogella tutorial on Mockito and get stuck pretty much immediately. IntelliJ displays cannot resolve method 'when' for the class below.

...what did I miss?

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest  {

@Test
public void test1()  {
    MyClass test = Mockito.mock(MyClass.class);
    // define return value for method getUniqueId()
    test.when(test.getUniqueId()).thenReturn(43);

    // TODO use mock in test.... 
}

}
like image 337
abc32112 Avatar asked Aug 12 '14 15:08

abc32112


People also ask

What does Cannot resolve method mean?

As before cannot resolve symbol means the java compiler cannot find the symbol it shows you on the symbol line. In this case it cannot find a method called Println for the object out . This is true, there is no such method, what we meant was println with a lowercase p.

Can we mock final methods using Mockito?

Before we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

What is Mockito doReturn?

You can use doReturn-when to specify a return value on a spied object without making a side effect. It is useful but should be used rarely. The more you have a better pattern such as MVP, MVVM and dependency injection, the less chance you need to use Mockito. spy .


1 Answers

The method when() is not part of your class MyClass. It's part of the class Mockito:

Mockito.when(test.getUniqueId()).thenReturn(43);

or, with a static import:

import static org.mockito.Mockito.*;

...

when(test.getUniqueId()).thenReturn(43);
like image 161
JB Nizet Avatar answered Sep 19 '22 14:09

JB Nizet