[PowerMock,当弹簧组件构造函数出现新问题时

问题描述 投票:0回答:1

我有如下所示的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();
    }
spring-boot junit powermock powermockito spring-boot-test
1个回答
0
投票

我已经解决了如下问题:

@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);
        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.