如何使用JUnit模拟条件?

时间:2019-03-19 18:58:35

标签: java junit mocking mockito powermockito

我正在尝试使用模仿方法模拟方法。如何使用Mockito模拟条件?

这是我的代码

@Override     公共RemedyWrapperOutput createRemedyTicket(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;
}

1 个答案:

答案 0 :(得分:0)

我认为您想看看您尝试模拟的方法。而不是方法的内容。让我用一个例子来解释。这是我要测试的简单类:

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;
  }
}

它会调用我要模拟的SomeDAO:

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行)为true的路径。因此,我没有嘲笑if语句,但是我通过仔细选择Mockito提供的返回值来强制执行特定的代码路径。