我有如下所示的Spring Service:
@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方法内部)调用它时,它将被触发。
有没有办法处理?
Works:
public void sendEmailEvent(Dto data)
{
this.mailAPI = new SendWithUs();
...
}
不起作用:
public SendWithUsService()
{
this.mailAPI = new SendWithUs();
}
我已经解决了如下问题:
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.net.ssl.*"})
@PrepareForTest(SendWithUsService.class)
public class SendWithUsServiceTest
{
@InjectMocks
private SendWithUsService sendWithUsService;
@Mock
private SendWithUs mailAPI;
@Before
public void setUp() throws Exception {
whenNew(SendWithUs.class).withAnyArguments().thenReturn(mailAPI);
MockitoAnnotations.initMocks(this);
}
@Test
public void sendEmailEvent_successfully() throws Exception
{
Dto emailData = ...;
sendWithUsService.sendEmailEvent(emailData);
...
}
}