我正在尝试使用Mockito模拟方法。如果使用Mockito,如何模拟条件?
这是我的代码
@Override public RemedyWrapperOutput createmedyticket(RemedyWrapperInput RemedyWrapperInput)抛出异常{
logger.info("Inside createRemedyTicket");
RemedyWrapperOutput result = new RemedyWrapperOutput();
final RemedyRecord remData = remedyDao.getByApiAndTitle(remedyWrapperInput.getInstance(),
remedyWrapperInput.getTitle());
/**
* if no records exists in the DB or if the RemedyStatus is
* CLOSED/RESOLVED/CANCELLED, we create a new ticket.
*/
if (remData == null ||remData.getStatus().equals(RemedyStatus.RESOLVED)
|| remData.getStatus().equals(RemedyStatus.CLOSED)|| remData.getStatus().equals(RemedyStatus.CANCELLED)) {
createRemedyTicket(remedyWrapperInput, result);
} else {
/* If record exists check if its within duration */
/**
* If not within time range create a ticket if New and Assigned
* status. For all other status stop processing.
*/
if (!checkIfInTimeRange(remData.getCreationDateTime())) {
if (remData.getStatus() != null && (remData.getStatus().equals(RemedyStatus.NEW)
|| remData.getStatus().equals(RemedyStatus.ASSIGNED)
|| remData.getStatus().equals(RemedyStatus.PENDING)
|| remData.getStatus().equals(RemedyStatus.IN_PROGRESS))) {
int id = remedyDao.create(createRemedyInput(remedyWrapperInput, remData));
callRemedyRestApi(remedyWrapperInput, result, id);
result.setMessage("Remedy request submitted");
}
} else {
result.setMessage("A request of this category has already been logged inside specified time range.");
}
// Update the last update time to current time
remedyDao.update(remData);
}
return result;
}
我想您想查看要模拟的方法。而不是该方法的内容。让我用一个示例解释。这是我想测试的简单课程:
package com.diffblue.javademo;
public class ClassToTest {
private boolean beenChecked = false;
private SomeDAO someDAO = new SomeDAO();
public void checkActive(int id) {
if (someDAO.isActive(id)) {
beenChecked = true;
}
}
public boolean getBeenChecked() {
return beenChecked;
}
}
它打电话给我想模拟的某种程度:
package com.diffblue.javademo;
public class SomeDAO {
public boolean isActive(int id) {
if (id < 5) {
return true;
}
return false;
}
}
当我创建一个测试案例时,我会考虑我要测试的checkActive
路径,然后从isActive
中选择一个可以锻炼该路径的答案。例如:
package com.diffblue.javademo;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Matchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import static org.mockito.Mockito.when;
public class ClassToTestTest {
/**
* Test the positive side of the if statement in checkActive
*/
@PrepareForTest({SomeDAO.class})
@Test
public void positiveTest() throws Exception {
// Arrange
ClassToTest objectUnderTest = new ClassToTest();
SomeDAO someDAO = PowerMockito.mock(SomeDAO.class);
when(someDAO.isActive(Matchers.anyInt())).thenReturn(true);
int activeId = 3;
// Act
objectUnderTest.checkActive(activeId);
// Assert
Assert.assertTrue(objectUnderTest.getBeenChecked());
}
}
在这种情况下,我检查了IF语句(SomeDao第6行)为真的路径。因此,我没有嘲笑IF语句,但是我通过仔细选择Mockito给出的返回值强制了特定的代码路径。