【发布时间】:2020-07-10 01:34:52
【问题描述】:
我有一个如下的 Spring 服务:
@Service
public class SendWithUsService
{
private SendWithUs mailAPI;
public SendWithUsService()
{
this.mailAPI = new SendWithUs();
}
public void sendEmailEvent(Dto data)
{
try
{
SendWithUsSendRequest request = new SendWithUsSendRequest()...;
mailAPI.send(request);
}
catch (Exception e)
{
...
}
}
}
我的测试代码如下所示:
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.net.ssl.*"})
@PrepareForTest(SendWithUsService.class)
public class SendWithUsServiceTest
{
@InjectMocks
private SendWithUsService sendWithUsService;
@Mock
private SendWithUs mailAPI;
@Test
public void sendEmailEvent_successfully() throws Exception
{
whenNew(SendWithUs.class).withAnyArguments().thenReturn(mailAPI);
Dto emailData = ...;
sendWithUsService.sendEmailEvent(emailData);
...
}
}
在这里,PowerMock whenNew 方法不起作用。但是当我在构造函数之外调用它时,比如在 sendEmailEvent 方法中,它会被触发。
有办法处理吗?
作品:
public void sendEmailEvent(Dto data)
{
this.mailAPI = new SendWithUs();
...
}
无效:
public SendWithUsService()
{
this.mailAPI = new SendWithUs();
}
【问题讨论】:
标签: spring-boot junit powermock powermockito spring-boot-test