Inject strings via Mockito

Viewed 5029

In my class under the test BusinessFlow I have some private service fields and one private field with java String type.

In my test class I have

@RunWith(MockitoJUnitRunner.class)
public class BusinessFlowTest {
    // How can I mock or spy this?
    private String code = "codeValue";
    @Mock
    private Service1Api service1;
    @Mock
    private Service2Api service2;
    @InjectMocks
    private BusinessFlow flow;
    ...
}

@InjectMocks and @Mock annotations greatly create mocks and inject service fields. But how can I create a mock for code field as Mockito doesn't allow to create a mock for final classes?

One option I see is to use CharSequence interface instead of String field type but it needs to change code of BusinessFlow class and I don't like this idea.

UPDATE: class BusinessFlow is defined like this

@Service
public class BusinessFlow {
    @Autowired
    @Qualifier(value = "clientCode")
    private String code;

    @Autowired
    private Service1Api service1;
    @Autowired
    private Service2Api service2;

    ...
}

and for some reason we don't use Spring Integration tests ability and don't want to rework BusinessFlow in different type of injection (e.g. ctor injection)

4 Answers

use apache commons reflection method to initialise string value in your test class as below

FieldUtils.writeField(classObject, "variableName", "value", true);

Related