简体   繁体   中英

How to get a value from a void method using Mockito - Groovy / java

Need some help with this question.

I have a Void method like this

    public void doSomething(String a, String b){
    ServiceUtils utils = new ServiceUtils(persistService, randomService)

    String c; 
    String d; 
    c = utils.someMethod(a, b); 
    d = service.anotherMethod(b, null);
    if(utils.validateSomething(d)){
    //...
    }



    persistService.persistMethod(c , d);

    }

I need to take the value inside C to move on with my groovy test.

Can't mock utils, its important to the validation. Can't mock/( spy(?)) persistService because is used in the utils constructor.

How could I do that using mockito?

The problem is the 'new' in your method:

ServiceUtils utils = new ServiceUtils(persistService, randomService)

Try to refactor your code: if you inject the 'ServiceUtils' class in the constructor, you will be able to mock this in the test.

You could use BDDMockito.verify() and ArgumentCaptor for that, like this:

ArgumentCaptor<String> capture = ArgumentCaptor.forClass(String.class);
BDDMockito.verify(persistService).persistMethod(captor.capture(), any()); 

And get the value with:

captor.getValue()

This assumes that persistService is mocked with Mockito.

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