我正在使用spring工具套件写一个代码,有4层restContoller,业务逻辑,域,服务...我想测试一个业务逻辑层的方法,它调用了一个to的方法,最后调用一个服务层的方法来返回一个简单的原始值……为了清楚地表明,在业务逻辑类中,我有自动连接的域类,在域类中,我已经自动连接了我所面临的服务classs..the问题。当我运行测试类时,我得到了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);
}
}发布于 2020-12-05 23:30:20
由于您正在扩展MockitoExtension,因此这个测试类不知道spring。但是你仍然在使用@Autowired注解。所以这是错误的。删除测试类中的所有@AUtowired注释。除此之外,您不需要引入所有的sterotyped类。只引入类正在使用的类,即在您的示例中注入到CustomerBl类中的类。我认为那应该是CustomerService类。因此,如果CustomerBl类中没有使用CustomerDO类,则将其删除。@InjectMock和@MOck注释已正确应用。我认为这应该会帮助你得到你的结果。
发布于 2020-12-05 23:42:27
您需要使用@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);
}
}https://stackoverflow.com/questions/61279695
复制相似问题