我有一个SpringBoot应用程序,其中进行了一些测试。我有这个Junit测试:
和测试:
public class FindHotelDataRequestTransformerTest {
@Autowired
private BackendHotelService backendHotelService;
private FindHotelDataRequestTransformer transformer;
@Before
public void setUp() {
transformer = new FindHotelDataRequestTransformer( backendHotelService);
}
@Test
public void theTest() {
mock(BackendHotelService.class);
when(transformer.getHotelApplicationName()).thenReturn("NameMocked");
...
}
}
这是基于以下类别:
public abstract class HotelDataRequestTransformer {
private final BackendCredentialsService backendCredentialsService;
public HotelDataRequestTransformer(BackendCredentialsService backendCredentialsService) {
this.backendCredentialsService = backendCredentialsService;
}
public String getHotelApplicationName() {
return backendCredentialsService.getHotelApplicationName();
}
}
@Component
public class FindHotelDataRequestTransformer extends HotelDataRequestTransformer {
public FindHotelDataRequestTransformer(BackendHotelService backendHotelService) {
super (backendHotelService);
}
..
}
但是当我运行测试时,我在行中得到了一个空指针
return backendCredentialsService.getHotelApplicationName();
所以看来Mocking.when不起作用
答案 0 :(得分:2)
从模拟本身而不是被测类返回
backendHotelService = mock(BackendHotelService.class); // also use the mock created :)
when(backendHotelService.getHotelApplicationName()).thenReturn("NameMocked");
答案 1 :(得分:0)
transformer不是您要创建新转换器的模拟对象。
backendHotelService是模拟对象。
尝试:
when(backendHotelService.getHotelApplicationName()).thenReturn("NameMocked");