PowerMockRunner和ActiveObjectsJUnitRunner

Jira的二次開發,須要做單元測試。spring

測試跟數據庫鏈接的類,好比service類,須要在類上加@RunWith(ActiveObjectsJUnitRunner.class).數據庫

有時須要搭配mockito使用,jira裏好像是內置了mockito仍是怎麼回事,不用再類上加@RunWith(MockitoJUnitRunner.class),也能夠模擬類api

可是當有須要模擬類的靜態方法和私有方法時,mockito就使不上力了,這是須要導入PowerMock。可是@RunWith只能接收一個參數,並且也不能再類上使用兩個@RunWith。ide

查閱資料,找到一個博客 單元測試

Using another JUnit Runner with PowerMock

裏面有降到如何在使用PowerMockRunner,能夠接着使用其餘Runner,樣例裏是SpringJUnit4ClassRunner測試

 1 package org.powermock.examples.spring.mockito;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.powermock.core.classloader.annotations.PowerMockIgnore;
 6 import org.powermock.core.classloader.annotations.PrepareForTest;
 7 import org.powermock.modules.junit4.PowerMockRunner;
 8 import org.powermock.modules.junit4.PowerMockRunnerDelegate;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.test.context.ContextConfiguration;
11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12 import powermock.examples.spring.IdGenerator;
13 import powermock.examples.spring.Message;
14 import powermock.examples.spring.MyBean;
15 
16 import static org.junit.Assert.assertEquals;
17 import static org.powermock.api.mockito.PowerMockito.*;
18 import static org.powermock.api.support.membermodification.MemberMatcher.method;
19 import static org.powermock.api.support.membermodification.MemberModifier.stub;
20 import static org.powermock.api.support.membermodification.MemberModifier.suppress;
21 
22 @RunWith(PowerMockRunner.class)
23 @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
24 @ContextConfiguration("classpath:/example-context.xml")
25 @PrepareForTest(IdGenerator.class)
26 public class SpringExampleTest {
27 
28     @Autowired
29     private MyBean myBean;
30 
31     @Test
32     public void mockStaticMethod() throws Exception {
33         // Given
34         final long expectedId = 2L;
35         mockStatic(IdGenerator.class);
36         when(IdGenerator.generateNewId()).thenReturn(expectedId);
37 
38         // When
39         final Message message = myBean.generateMessage();
40 
41         // Then
42         assertEquals(expectedId, message.getId());
43         assertEquals("My bean message", message.getContent());
44     }
45 }
View Code

可是,本身在使用時,並未生效spa

1 PowerMockito.doAnswer(e -> {
2             String key = (String) e.getArguments()[0];
3             。。。
4             }
5         }).when(exportEmployeeCSV, "getSex", anyString());

目的是模擬私有方法,而且不執行私有方法內部的代碼,可是屢次調整代碼仍是會執行內部代碼。code

繼續看評論,好像是版本問題xml

 

 修改成最新版本,從新運行測試用例,Green Bar!blog

相關文章
相關標籤/搜索