junit测试用例

zc0qhyus  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(328)

如何测试我的服务类 storeInDb() 方法并返回数据库模型和 httpstatus.OK 以及 httpstatus.Bad_Request 还有尸体。

public ResponseEntity storeInDb(ExeEntity model) {
    Validator validation = new Validator();
    Map objValidate = validation.validateInput(model.getLink(), model.getUsername(), model.getPassword(),
            model.getSolution(), model.getDomain());
    if (objValidate.containsKey("Success")) {
         return new ResponseEntity(model, HttpStatus.OK);
    }
    else if (objValidate.containsKey("Fail")) {
        if (objValidate.containsValue("Invalid Credentials")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Credentials");
    } }
    else {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Domain does not exist.");
    } 
}

请帮我回答这个问题和写测试用例。提前谢谢。

rseugnpd

rseugnpd1#

在当前的代码设计中,单元测试非常困难。方法的完整逻辑基于 ExeEntityValidator . 换句话说,它依赖于它。这种依赖关系应该在单元测试中模拟掉。
为了模拟这个验证器,您应该应用依赖注入。这意味着您需要提供依赖项,而不是自己在需要的地方创建依赖项。这是通过将依赖项传递到类的构造函数并将其存储为成员变量来实现的。
如果您这样做,您的测试代码可能如下所示:

void test(){

    // mock a ExeEntityValidator that is used inside your '::storeInDb' method
    Map<String, Object> objValidated = Map.of("Success", true);
    var validator = mock(ExeEntityValidator);
    doReturn(objValidated).when(validator).validateInput(any(ExeEntity.class));

    // instantiate your component with the mocked ExeEntityValidator
    var cut = new UnknownClass(validator);
    var model = new ExeEntity(...);

    // call the method you want to test
    var response = cut.storeInDb(model);

    assertEquals(HttpStatus.OK, response.getStatusCode());
}

相关问题