我正在尝试为助手类创建测试,但无法在助手类内部模拟静态调用。
这是我要测试的课程:
public class NoteHelper {
private NoteService noteService = ServiceBuilder.getService(NoteService.class);
public NoteResponse createNewNote(NoteRequest noteRequest) throws NotAuthorizedException {
Note note = new Note();
note.setContent(noteRequest.getContent());
noteService.addNote(note); // throws NotAuthorizedException
NoteResponse noteResponse = new NoteResponse();
noteResponse.setContent(note.getContent());
return noteResponse;
}
}
这是我的考试班:
@RunWith(PowerMockRunner.class)
public class NoteServiceHelperTest {
String dummyContent = "ABCD";
@InjectMocks
private NoteHelper noteHelper;
@Mock
private NoteService noteService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
@PrepareForTest({NoteHelper.class, ServiceBuilder.class})
public void createNewNoteTest() throws NotAuthorizedException {
noteService = Mockito.mock(NoteService.class);
PowerMockito.mockStatic(ServiceBuilder.class);
PowerMockito.when(ServiceBuilder.getService(NoteService.class))
.thenReturn(noteService);
doNothing().when(noteService).addNote(any(Note.class));
NoteRequest request = new NoteRequest();
request.setContent(dummyContent);
NoteResponse response = noteHelper.createNewNote(request);
assertEquals(response.getContent(), dummyContent);
}
}
根据我的阅读,我认为对ServiceBuilder.getService(...)
的调用将被替换,而noteService
将使用模拟实例而不是真实实例。
问题是这种情况没有发生,实际上由于某些外部系统依赖性而实际上调用了getService(...)
方法,并最终失败了(ServiceBuilder.getService(...)
需要获取一些数据库连接并对其他系统进行HTTP调用返回NoteService
实例之前。
所以我的问题是我如何使用Power Mockito模拟getService(...)
和noteService.addNote(note)
调用?