Search code examples
javaunit-testingmockingmockitojunit4

Mockito: Java - Is it possible to Change a variable value used in an InjectMocks class?


I am wondering if this is possible. I have tried a few implementations using @mock and @spy to create a new string that has the same variable name as the one in a injectMocked class however I get the following error:

Cannot mock/spy class java.lang.String
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types

In the class that is being used in InjectMocked I have:

public class Service{

   String url = getUrl();

   ...
}

However I want to use a different url for testing as we have one for a testing environment.

I have tried things such as:

@Mock
private String url = "myUrlString";

@Spy
private String url = "myUrlString";

What I want is for when I run my Test the new value for url will be injected into the inJectMock and will be used instead of the other one.

Example:

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest{
    @Mock // or similar
    private String url = "http://....";

    @InjectMocks
    private Service service = new Service();
}

So when the test runs the class is like this:

public class Service{

   // Uses the inject url instead of the method that it originally uses
   String url = "http://....";

   ...
}

Is this possible? If so how and if not how come? I can't be the only person to think to do this, however I cannot find any documentation on it.


Solution

  • You should just set the url with your test value, like service.setUrl(testUrl);. Mockito is not intended to provide mock values for variables, but to provide mocked implementations of methods you don't want to run in your unit tests.

    For example if you have a class like this:

    public class UrlProvider {
        public String getUrl(){
            return "http://real.url";
        }
    }
    

    and you use it in your service:

    public class Service{
    
        UrlProvider provider;
    
        public Service(UrlProvider provider){
           this.provider = provider;
        }
    
    
    
       ...
    }
    

    then you can easily change the returned value of the getUrl method:

    @RunWith(MockitoJUnitRunner.class)
    public class ServiceTest{
        @Mock 
        private UrlProvider urlProvider;
    
        @InjectMocks
        private Service service = new Service();
    
        @Before
        public void init(){
            when(urlProvider.getUrl()).thenReturn("http://test.url");
    
        }
        ...
    }