1

I'm testing my spring controller and trying to do the following

Controller

Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    String role = String.valueOf(authentication.getAuthorities());
    if(role.contains("user")) {
        ...
    }

Test

@Test
public void testLoginUser() throws Exception {
    User user = new User();
    user.setLogin("user");
    user.setRoleid(1L);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user,user));
    when(String.valueOf(Collection.class)).thenReturn("user");

But I get

org.mockito.exceptions.misusing.MissingMethodInvocationException

I need my if block to be true and execute.
Is there any way it can be done?

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
qiGuar
  • 1,726
  • 1
  • 18
  • 34
  • Did you look at PowerMock? See https://code.google.com/p/powermock/wiki/MockStatic and https://code.google.com/p/powermock/wiki/MockFinal . – Glory to Russia Sep 25 '13 at 11:05

2 Answers2

6

Because
1. String class is final and you cant mock final classes with Mockito.
2. String.valueOf is a static metod and you cant mock static method with Mockito

From Mockito FAQ

What are the limitations of Mockito

Needs java 1.5+
Cannot mock final classes    // String is Final
Cannot mock static methods... // String.valueOf is static

Either mock authentication.getAuthorities() method or use Powermock.

This link might help.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
1

String.valueOf is a static method and is not mocked by Mockito. Your expression will simply resolve to a String instance with the value "class java.util.Collection".

Why does Mockito not mock static methods?.

Community
  • 1
  • 1
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436