如何在 Spring 引导中模拟服务 Class 以用于测试另一个服务 Class? JUNIT 5

How to Mock a Service Class in Spring Boot to be used in the testing of another Service Class? JUNIT 5

我有两个服务 ServiceOne.classServiceTwo.class。 我正在尝试模拟 ServiceTwo,但没有在线解决方案有效,并且在 ServiceOne.class 的测试中,尽管明确提及它,但它就像没有得到任何结果一样。

我知道有很多类似的解决方案,但是 none 的解决方案对我有用。

methodTest 是我应该测试的 ServiceOne.class 中的方法。


@SpringBootTest
class ServiceOneTest {

    @MockBean
    private Repo1 repo1;
    @MockBean
    private Repo2 repo2;
    @MockBean
    private Repo3 repo3;
    @MockBean
    private Repo4 repo4;
    @MockBean
    private Repo5 repo5;
    @MockBean
    private Repo6 repo6;
    @MockBean
    private Repo7 repo7;
    @MockBean
    private Repo8 repo8;
    @MockBean
    private Repo9 repo9;
    @MockBean
    private Repo10 repo10;
    @MockBean
    private Repo11 repo11;

    @MockBean
     private ServiceTwo serviceTwo;

    @Autowired
    private ServiceOne serviceOne;

@BeforeEach
    void setUp() throws Exception { 
//static objs1-11 and serviceObj to be returned as mock data here
}

@AfterEach
    void tearDown() throws Exception {
}

@Test
    void methodTest() throws JsonProcessingException {
   when(repo1.findAll()).thenReturn(obj1);
   when(repo2.findAll()).thenReturn(obj2);
   //for other repo3...repo11
   when(repo11.findAll()).thenReturn(obj11);
   
  when(serviceTwo.getObj(params).thenReturn(serviceObj);

  String result= serviceOne.method();
  assertEquals(expectedResult, result);
}

没有返回 serviceObj,因此代码片段抛出错误,没有到达 assert 语句。

我有两个服务 类:ServiceAServiceB

ServiceA 有一个 getInteger() 总是 returns 5 ServiceB 有一个 getLong() 调用 ServiceA 上的 getInteger() 和 returns 长值。

ServiceA

@Service
public class ServiceA {

    public Integer getInteger() {
        return 5;
    }

}

ServiceB

@Service
public class ServiceB {

    @Autowired
    ServiceA serviceA;

    public Long getLong() {
        return serviceA.getInteger().longValue();
    }

}

下面是我的单元测试:

ServiceATest

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class ServiceATest {


    @Autowired
    ServiceA serviceA;

    @Test
    void getInteger() {

        assertThat(serviceA.getInteger()).isEqualTo(5);
    }
}

ServiceBTest

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

@SpringBootTest
class ServiceBTest {

    @Autowired
    ServiceB serviceB;

    @MockBean
    ServiceA serviceA;



    @Test
    void getLong() {

        when(serviceA.getInteger()).thenReturn(7);
        assertThat(serviceB.getLong()).isEqualTo(7L);

    }
}