【发布时间】:2019-08-25 09:52:53
【问题描述】:
我有一个 JobDelegate 类,我正在使用 mockito 为其编写单元测试。我无法模拟 HTTPOperations 类。我也尝试过使用来自测试类的 setter 注入。但它不起作用。下面是最新版本的代码。我尝试使用 Power mock。但他们都没有帮助。我无法预测哪个出了问题。
单元测试代码
@ContextConfiguration(locations= "file:src/main/webapp/WEB-INF/spring-
context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
//@RunWith(PowerMockRunner.class)
/@PowerMockIgnore({ "javax.xml.*", "org.xml.*", "org.w3c.*" })
//@PrepareForTest({ HTTPOperations.class})
public class JobSubmissionDelegateTest{
private static Logger LOGGER = null;
private JobDelegate jobDelegate ;
private JobManager jobImpl;
@InjectMocks
private HTTPOperations operations;
//@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Before
public void setupTests() {
jobDelegate = new JobDelegate();
jobManager = new DBJobManagerImpl();
operations = new HTTPOperations();
jobManager.setHttpOperations(operations);
jobSubmissionDelegate.setJobImpl(jobManager);
//HTTPOperations httpOperationsSpy =spy(HTTPOperations.class);
//doReturn("{\"response\":\"{\\\"run_id\\\":32423423}\\n\"}").when(myClassSpy).method1();
MockitoAnnotations.initMocks(this);
}
@Test
public void testExecuteJob() throws IOException {
// PowerMockito.mockStatic(HTTPOperations.class);
Mockito.when(operations.submitHttpPostRequest(any(), anyString())).thenReturn("{\"response\":\"{\\\"run_id\\\":32423423}\\n\"}");
//System.out.println("==>"+operations.submitHttpPostRequest(null, ""));
...........
int runID = jobDelegate.executeJob(jobDetails);
System.out.println("Run ID here " + runID);
}
}
public class JobDelegate {
// This is an interface.. and the implementation is passed from spring-
context.xml
@Autowired
private JobManager jobImpl;
public int executeJob(JobDTO jobDto) {
............
return jobImpl.runBatchJob(jobDto);
}
}
public class DBJobManagerImpl implements JobManager{
@Autowired
private URIUtils uriUtils;
@Autowired
private HTTPOperations httpOperations;
@Override
public int runBatchJob(JobDTO jobDto) throws Exception {
UriComponentsBuilder uri = uriUtils.createURI(ConfigUtil.getUrI());
String response = httpOperations.submitHttpPostRequest(uri, runSubmitJson);
System.out.println("Response ==> " +response);
.................
}
}
【问题讨论】:
-
InjectMocks 用于创建一个 real 实例并将 inject 模拟到这个真实实例中。它没有嘲笑任何东西。阅读 Mockito 文档。而且您没有在测试中自动装配任何 bean,那么使用 RunWith 和 ContextConfiguration 进行注释有什么意义呢?最后,如果您要测试的是 JobDelegate 类,您为什么要尝试模拟 HTTPOperations? JobDelegate 不直接依赖于 HTTPOperations。这取决于 JobManager。这就是你应该嘲笑的。
-
我需要模拟 HTTPOperations 来覆盖 jobManager 实现的测试。