issue with openmocks()参数应该是模拟的,但是是:class org.springframework.data.jpa.repository.support.simplejparepository

eqoofvh9  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(383)

我在尝试添加自动连线接口jpa repo的对象时遇到了这个问题。我已经更新了SpringBoot2.2.5版本。发布到2.4.1/Java11和JUnitJupiter。我同时使用@spy和@autowire来模拟jpa存储库,因为initmocks()不受欢迎,所以我使用mockito.openmocks()
这是一个投掷错误

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class org.springframework.data.jpa.repository.support.SimpleJpaRepository
    at com.test.services.SampleServiceTest.setUp(SampleServiceTest.java:89)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)

@ExtendWith(SpringExtention.class)
@SpringBootTest(classes = TestServer.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("test")
@Transactional
SampleServiceTest {

@Spy
@Autowire
private TestRepo repo;
@Mock
SpecialTest test;
@Mock
SpecialTest1 test1;
@InjectMock
TestServiceTest testService;

@InjectMock
SampleServiceTest sampleServiceTest;

@BeforeEach()
void setup () {
openMocks(this);
when(testService.getId()).thenReturn(test);
when(testService.getId()).thenReturn(test1);
}
@Test
void test () {

}

我试过上述方法

3xiyfsfu

3xiyfsfu1#

您应该将@mock用于simplejpeppository,将@injectmock用于在构造函数中采用simplejpeppository的类。此外,您应该使用initmocks(this)例如:

class TestClass {

    @Mock
    private SimpleJpaRepository repo;

    @InjectMocks
    private YourService service;

    @Before
    void setUp(){
      initMocks(this)
    }

    @Test
    void repoTest(){
    }
}

用于初始化mock。
服务示例:

class YourService {

    private SimpleJpaRepository repo;

    public YourService (SimpleJpaRepository repo){
      this.repo = repo;
  }
}

相关问题