简体   繁体   中英

Unit testing Exception scenarios with cucumber in java

I am following BDD apprach and using cucumber to perform unit testing I have a class as given below

public class EmployeeServiceImpl {

private static Log log = LogFactory.getlog(EmployeeServiceImpl.class);

@Autowired
private EmployeeDao employeeDao;

public void saveEmployee(Employee emp) throws Exception {
    try {
employeeDao.saveemployee(emp);
      } catch (Exception ex) {
            log.error("Error occured "+ex);
      }
  }
}

Can anyone please help me how to write exception scenario for the above code snippet?

The algorithm I would use is something like this:

  • Prepare the argument emp so it will throw the expected error
  • Call the method
  • Verify that the interaction with the log happened

I would use Mockito for verifying the interaction, http://site.mockito.org/#how

A JUnit solution could look like this:

@Test
public void verify_logging() throws Exception {
    Log log = mock(Log.class);

    Employee emp = new Employee();

    saveEmployee(emp);

    verify(log, times(1)).error("Error occured");
}

Transforming this to Cucumber with three steps would be something like this:

private Log log;
private Employee emp;

@Given("prepare employee")
public void given() {
    Log log = mock(Log.class);

    Employee emp = new Employee();
}

@When("save employee")
public void when() throws Exception {
    saveEmployee(emp);
}

@Then("exception should be logged")
public void then() {
    verify(log, times(1)).error("Error occured");
}

Your task is to come up with better names for the step methods as well as better steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM