简体   繁体   中英

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?

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.

You never instantiated your test class's properties.

private Model model = new Model(<params>)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM