У меня есть репозиторий MyRepository
, который @Repository
. Этот репозиторий используется одним из моих контроллеров отдыха. Я хочу проверить, правильно ли работает авторизация моего контроллера покоя, поэтому мои тесты используют @WithUserDetails
. Я хочу издеваться над MyRepository
, следуя этому уроку . Когда я запускаю свои тесты, я получаю исключение:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
В результате некоторой отладки я обнаружил, что мой MockConfig#myRepository
метод не вызывается.
SRC / главная / Java / com.example
MyRepository
@Repository
interface MyRepository extends CrudRepository<MyEntity, Long> {}
SRC / тест / Java / com.example
MockConfig
@Profile("test")
@Configuration
public class MockConfig
{
@Bean
@Primary
public MyRepository myRepository()
{
return Mockito.mock(MyRepository.class);
}
}
MyTestClass
@ActiveProfiles("test")
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class
})
class MyTestClass
{
@Autowired
private MockMvc mvc;
@Autowired
private MyRepository myRepository;
@Test
@WithUserDetails("some_user")
public void testWithCorrectPermissions()
{
long entityId = 1;
MyEntity mockReturnValue = new MyEntity();
Mockito.when(myRepository.findOne(entityId)).thenReturn(mockReturnValue);
Mockito.when(myRepository.save(mockReturnValue)).thenReturn(mockReturnValue);
this.mockMvc.perform(post("my/api/path")).andExpect(status().isOk());
}
}