N.Zukowski
N.Zukowski

Reputation: 601

Use static initialization block with Mockito

I am starting up with Mockito as my mocking framemork. I try to mock some custom class with it:

//usage
@Mock
private LoginAttempt loginAttempt;

and the LoginAttempt class:

public class LoginAttempt {
    private static LoginAttempt loginAttempt;

    static {
        loginAttempt = new LoginAttempt();
        loginAttempt.setOs(TEST_GLOBALS.OS);
        loginAttempt.setBrowser(TEST_GLOBALS.BROWSER);
        loginAttempt.setDevice(TEST_GLOBALS.DEVICE);
        loginAttempt.setOsVersion(TEST_GLOBALS.OS_VERSION);
        loginAttempt.setBrowserVersion(TEST_GLOBALS.BROWSER_VERSION);
    }
...

But when I debug my test cases, the loginAttempt var is empty. What am I doing wrong?

I saw in tutorials, that I should do something like this:

private static LoginAttempt loginAttempt = new LoginAttempt();

But what if I want to preinitialize some field values?

EDIT my loginAttempt is not null, but the values I assigned in the static block are not initialized.

Upvotes: 0

Views: 6156

Answers (1)

AlexC
AlexC

Reputation: 1415

While it's good to know the difference between Mock and Spy, the real reason is in the edit below. Otherwise see What is the difference between mocking and spying when using Mockito? for more info about the difference.

EDIT: I noticed you are missing the annotation to enable mockito on a class:

@RunWith(MockitoJUnitRunner.class)
public class LoginAttemptTest {
    @Mock
    LoginAttempt loginAttempt;

    @Test
    public void testObjectExistence() {
        System.out.println("loginAttempt="+loginAttempt);
    }
}

Upvotes: 1

Related Questions