class MyService {
private UserDao userDao;
}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
public class MyServiceTest {
@InjectMocks
private MyService myService;
@Mock
private UserDao userDao;
@Before
public void setUp() {
myService = new MyService();
}
}
Cannot mock/spy class java.lang.String Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.lang.String
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
In case you have to mock String, perhaps you can add a function only visible for testing via
import com.google.common.annotations.VisibleForTesting;
And in this function, mock the String type's value.
For Example:
class MyService {
private String name = "myservice";
@VisibleForTesting
void forTest(String mockName) {
this.name = mockName;
}
}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
public class MyServiceTest {
private MyService myService;
@Before
public void setUp() {
myService = new MyService();
myService.forTest("mockName");
}
}