【问题标题】:how to use junit and mockito when we have a mulit layer service call approach in a restfull web service当我们在 RESTful Web 服务中有多层服务调用方法时如何使用 junit 和 mockito
【发布时间】:2020-07-31 10:20:52
【问题描述】:

我正在使用spring工具套件编写代码。有4层restContoller,buisnesslogic,domain,service.... 我想测试一个业务逻辑层的方法,它调用一个dao的方法,最后调用一个服务层的方法来返回一个简单的原始值......为了在业务逻辑类中明确,我有自动装配的域类,并且在域类中,我已经自动连接了服务类..当我运行测试类时我面临的问题是 NullPointerException 我正在附加测试类的代码……如果可能,请提供帮助

@ExtendWith(MockitoExtension.class)
class CustomerBlTest {
    @Mock
    CustomerService mockService;
    @Autowired
    CustomerDO customerDo;

    @Autowired
    @InjectMocks
    CustomerBl bl;       //buisnesslogic class
    @Test
    void checkForGetInteger() {
        when(mockService.getIntegerFfromService()).thenReturn(3);

        int actual = bl.getInteger();
        Assertions.assertEquals(3, actual);
    }
}

【问题讨论】:

    标签: spring-boot testing junit mockito spring-mvc-test


    【解决方案1】:

    由于您正在扩展 MockitoExtension,因此该测试类不知道 spring。但是您仍在使用 @Autowired 注释。所以这是错误的。删除测试类中的所有 @AUtowired 注释。除此之外,您不需要引入所有定型类。仅引入该类正在使用的类,即在您的情况下,注入 CustomerBl 类中的类。我认为应该是 CustomerService 类。因此,如果 CustomerBl 类中没有使用 CustomerDO 类,请删除它。 @InjectMock 和 @MOck 注释已正确应用。我认为这应该可以帮助您获得结果。

    【讨论】:

      【解决方案2】:

      您需要使用@Mock 而不是@Autowired,如下所示。

      @ExtendWith(MockitoExtension.class)
      class CustomerBlTest {
          @Mock
          CustomerService mockService;
      
          @Mock
          CustomerDO customerDo;
      
         
          @InjectMocks
          CustomerBl bl;       //buisnesslogic class
      
          @Test
          void checkForGetInteger() {
              when(mockService.getIntegerFfromService()).thenReturn(3);
      
              int actual = bl.getInteger();
              Assertions.assertEquals(3, actual);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 1970-01-01
        • 2011-07-08
        • 2020-03-17
        • 2022-11-11
        相关资源
        最近更新 更多