【问题标题】:PowerMock whenNew Problem On Spring Component ConstructorPowerMock whenNew Problem On Spring Component Constructor
【发布时间】: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


    【解决方案1】:

    我已经解决了如下:

    @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);
            ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-29
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多