0

how can i initialize user so i can do the user.getUserId() without findbugs warning?

Uninitialized read of user in new .service.MockUserService() [.service.MockUserService] At MockUserService.java:[line 21]

public class MockUserService extends UserService {

    public static final String FOO_USER_ID = "fooUser";

    @Mock
    private User user;


    public MockUserService() {
        super();
        MockitoAnnotations.initMocks(this);
        Mockito.when(user.getUserId()).thenReturn(FOO_USER_ID);
    }

    @Override
    public User getUser() {
        return getUserSafe();
    }

    @Override
    public User getUserSafe() {
        return user;
    }
}
Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75

1 Answers1

3

I don't know much findbugs, since I use sonar. For static code analysis tools I usually find default rules not always the best so I tend to tweak them and update them for the new development pattern.

Anyway for findbugs, googling around gave two possible solution

  • Use findbug annotation on each field (findbugs 3.0.0)

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
        value="UR", 
        justification="This is an auto injected mock")
    
  • Or set a filter to ignore the Mock annotation.

    <Match>
       <Bug code="UR">  
       <Field annotation="Mock">
    </Match>
    

Note that both of these is pseudo code, I'm writing from a smartphone. So there may be missing mandatory statements and/or the rule (UR) may be wrong, the bug description is on the findbug website.

These ideas mostly came from :

  1. Is there a way to ignore a single FindBugs warning?
  2. http://www.scriptscoop2.com/t/0044ed425b4f/java-how-to-set-a-findbugs-filter-for-fields-with-a-specific-annotation.html
  3. http://findbugs.sourceforge.net/bugDescriptions.html

I'd like to point out that the way mockito is used in this example does seem wrong. Here's my recommendation :

  1. User is either an entity or a value object I strongly advise to not mock such classes. For these I prefer to use builders. Usually I craft a test builder that can be used like that UserBuilder.userWithId(73L).build()
  2. And finally instead mock UserService to return the preconfigured user BDDMockito.given(user_service_mock.getUser()).willReturn(preconfigured_user)
Community
  • 1
  • 1
bric3
  • 40,072
  • 9
  • 91
  • 111