How to use @Mock @InjectMocks

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");
    }
}

Comments

  1. Your Affiliate Profit Machine is waiting -

    And earning money online using it is as simple as 1 . 2 . 3!

    Here is how it all works...

    STEP 1. Choose which affiliate products you want to push
    STEP 2. Add push button traffic (it LITERALLY takes 2 minutes)
    STEP 3. See how the system explode your list and upsell your affiliate products all for you!

    Are you ready to make money ONLINE??

    Your MONEY MAKING affiliate solution is RIGHT HERE

    ReplyDelete

Post a Comment

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)