我有一个实现类,它实现一个接口并覆盖其方法。实现类获取类的单例实例,需要在JUnit中对其进行模拟。我尝试使用PowerMock,但在这里无法正常使用。 另外,在运行此处提到的测试时,我得到此处提到的错误:https://codeshare.io/5NyJyr
这是实现类:
@Slf4j
@Component
public class PhoneServiceImpl implements NotificationService {
private String notificationServiceURL;
private PhoneContext phoneContext;
public PhoneServiceImpl(@Value("${notificationService.url}") String notificationServiceURL) {
this.notificationServiceURL = notificationServiceURL;
}
@Override
public void sendPhoneSMSByEmployeeIds(String title, String message, List<String> employeeIds) {
log.info("Sending notifications by Employee Id");
SendNotificationByEmployeeIds sendNotificationByEmployeeIds = SendNotificationByEmployeeIds.getInstance();
sendNotificationByEmployeeIds.setNotificationServiceURL(notificationServiceURL);
phoneContext = new PhoneContext(sendNotificationByEmployeeIds);
phoneContext.notify(title, message, employeeIds);
}
}
测试:
public class Test {
PhoneServiceImpl phoneServiceImpl;
@Mock
PhoneContext phoneContext;
@Value("${phoneService.url}")
String phoneServiceUrl;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
phoneServiceImpl = new PhoneServiceImpl("some");
}
@org.junit.jupiter.api.Test
void simpleTest() {
phoneServiceImpl.sendPhoneSMSByEmployeeIds(anyString(), anyString(), anyList());
verify(phoneContext, Mockito.times(1)).notify(anyString(), anyString(), anyList());
}
}