首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当我们在restfull web服务中使用多层服务调用方法时,如何使用junit和mockito

当我们在restfull web服务中使用多层服务调用方法时,如何使用junit和mockito
EN

Stack Overflow用户
提问于 2020-04-18 03:57:59
回答 2查看 76关注 0票数 1

我正在使用spring工具套件写一个代码,有4层restContoller,业务逻辑,域,服务...我想测试一个业务逻辑层的方法,它调用了一个to的方法,最后调用一个服务层的方法来返回一个简单的原始值……为了清楚地表明,在业务逻辑类中,我有自动连接的域类,在域类中,我已经自动连接了我所面临的服务classs..the问题。当我运行测试类时,我得到了NullPointerException,我附上了测试类的代码……如果可能的话,请帮忙。

代码语言:javascript
运行
复制
@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);
    }
}
EN

回答 2

Stack Overflow用户

发布于 2020-12-05 23:30:20

由于您正在扩展MockitoExtension,因此这个测试类不知道spring。但是你仍然在使用@Autowired注解。所以这是错误的。删除测试类中的所有@AUtowired注释。除此之外,您不需要引入所有的sterotyped类。只引入类正在使用的类,即在您的示例中注入到CustomerBl类中的类。我认为那应该是CustomerService类。因此,如果CustomerBl类中没有使用CustomerDO类,则将其删除。@InjectMock和@MOck注释已正确应用。我认为这应该会帮助你得到你的结果。

票数 0
EN

Stack Overflow用户

发布于 2020-12-05 23:42:27

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

代码语言:javascript
运行
复制
@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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61279695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档