如何用mockito在服务测试中模拟工厂方法



你好,我正在测试服务层。我已经为ConverterFactory写了测试。我想我需要ConverterServiceImpl使用的模拟依赖类,但我仍然得到了NullPointerException

这是我的服务类

@Service
@RequiredArgsConstructor
public class ConverterServiceImpl implements ConverterService {
ConverterFactory factory = new ConverterFactory();
private final WebLinkRepository webLinkRepository;
private final DeepLinkRepository deepLinkRepository;
@Override
public DeepLinkResponse toDeepLink(WebLinkRequest webLinkRequest) {
WebLink webLink;
String url = webLinkRequest.getUrl();
Converter converter = factory.getConverter(url);

webLink = new WebLink();
webLink.setUrl(url);
String convertedUrl = converter.toDeepLink(url);
webLink.setConvertedUrl(convertedUrl);
webLinkRepository.save(webLink);
return new DeepLinkResponse(convertedUrl);
}
}

这是测试

@RunWith(MockitoJUnitRunner.class)
public class ConverterServiceImplTest {

@InjectMocks
ConverterServiceImpl converterService;
@Mock
WebLinkRepository webLinkRepository;
@Mock
DeepLinkRepository deepLinkRepository;
@Mock
ConverterFactory converterFactory;
@Mock
ProductConverter productConverter;
@Mock
WebLinkRequest webLinkRequest;
@BeforeAll
void init(){
webLinkRequest.setUrl(WEBLINK_ONLY_PRODUCT);
}
@Test
public void toDeepLink_only_content_id() {
ConverterFactory converterFactory = mock(ConverterFactory.class);
when(converterFactory.getConverter(any())).thenReturn(productConverter);
DeepLinkResponse deepLinkResponse = converterService.toDeepLink(webLinkRequest);
assertEquals(deepLinkResponse.getUrl(),"ty://?Page=Product&ContentId=1925865");
}
}

这段代码抛出的错误如下:我哪里做错了?:

java.lang.NullPointerException
at com.example.converter.service.factory.ConverterFactory.getConverter(ConverterFactory.java:13)

您不需要在测试方法中第二次创建ConverterFactory converterFactory = mock(ConverterFactory.class),因为您已经创建了这样的mock作为类字段。

此外,您没有将在测试方法中创建的模拟注入到被测试的类中,而作为字段创建的模拟是使用@InjectMocks注释注入的。

所以只要从test method中删除ConverterFactory converterFactory = mock(ConverterFactory.class):

@RunWith(MockitoJUnitRunner.class)
public class ConverterServiceImplTest {

@InjectMocks
ConverterServiceImpl converterService;
@Mock
ConverterFactory converterFactory;
// other stuff

@Test
public void toDeepLink_only_content_id() {
when(converterFactory.getConverter(any())).thenReturn(productConverter);
// other stuff
converterService.toDeepLink(webLinkRequest);
}
}

最新更新