elpisu
elpisu

Reputation: 789

How to write Unit test with Mockito

I have a simple Controller that I would like to write a Mockito unit test for. Here is the code:

private final UserController userCtl;

public String get(final Model model) {
    return this.userCtl.getLoginForm(model);
}

Here is my test:

@Mock
private Model model;

private DefaultControllerImpl sut;

@Before 
public void setup() { 
    this.ctl = new DefaultControllerImpl(this.userCtl, this.authService, this.orgService, this.riskSpaceService); 
    this.ctl.setMessageSource(this.messageSource); 
}

@Test
public void testGet() {        
    final String view = this.sut.get(this.model);
    assertThat(view).isEqualTo(UserController.LOGIN_PATH);
}

However, this test always returns null. How can I go about writing a proper unit test for this controller?

Upvotes: 0

Views: 632

Answers (2)

Jonathan
Jonathan

Reputation: 20385

You don't say what is null but I'm assuming that none of your mocks are, so you must have declared the following runner on your test class:

@RunWith(MockitoJUnitRunner.class)

However what I can't see in your test is any behaviour added to the mocks. For example you are not telling usrCtl to return anything on a getLoginForm(...) call so it will return null by default - perhaps this is why you are seeing null.

To instruct the usrCtl mock to return the value you want you can do something like:

given(userCtl.getLoginForm(model)).willReturn(UserController.LOGIN_PATH);

You should take a look at the Mockito documentation, if you haven't done so already, for further information and examples.

Upvotes: 1

tonymke
tonymke

Reputation: 862

You never instantiated your test class's properties.

private Model model = new Model(<params>)

private DefaultControllerImpl sut = new DefaultControllerImpl(<params>);

Upvotes: 0

Related Questions