MockingHttpServlet请求对象给出java.lang.NoClassDefFoundError:jakar



我有一个控制器

@RestController
public class BodyController extends BaseController {
@Autowired
private BodyService bodyService;
@PostMapping(value = "/api/body")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Body Created", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = ReadBodyDto.class))}),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "401", description = "Unauthorized access", content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "409", description = "Conflict"),
@ApiResponse(responseCode = "412", description = "Precondition mismatched"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@Operation(summary = "Body", requestBody = @RequestBody(description = "The Body that will be created.", content = @Content(schema = @Schema(implementation = BodyDto.class))))
@SecurityRequirement(name = "bearerAuth")
public ResponseEntity<?> createBody(@org.springframework.web.bind.annotation.RequestBody BodyDto bodyDto,
HttpServletRequest request) {
handleJWT(request, false);
LOGGER.info(bodyDto.toString());
BodyValidator.validateBody(bodyDto);
Message<?> bodyResponse = bodyService.createBody(bodyDto, getToken());
return constructResponseEntity(bodyDto);
}

}

使用jMockit测试框架,我需要为这个控制器类编写一个单元测试和集成测试。

我试图使用org.springframework.mock.web.MockHttpServlet请求添加请求对象,但出现以下错误:

java.lang.NoClassDefFoundError:jakarta/servlet/ServletConnectioncom.package.BodyControllerTest$2。(BodyControllerTest.java:94)com.package.BodyControllerTest.createBody(BodyControllerTest.java:93)引起原因:java.lang.ClassNotFoundException:jakarta.servlet.ServletConnectionjava.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)

这是我的测试类

class BodyControllerTest {
protected String accessToken;
protected ResponseEntity<?> responseEntity;
protected MockHttpServletRequest request;
protected JsonNode createBody;


/**

* @Tested will specify the class is under testing
*/
@Tested
private BodyController bodyController;


/**
* @Capturing will create mocked instances of each and every new object of that particular class
* and also
* will extend its reach to every subclass extending or implementing the annotated field's type
*/


/**
* @Injectable only one mocked instance will be created
*/
@Injectable
private JwtModel jwtModel;

@Injectable
private BodyService bodyService;
@BeforeEach
void setUp() {
accessToken = "//confidential";
}
@AfterEach
void tearDown() {
responseEntity = null;
request = null;
}
@Test
void createBody() {
ClassLoader classLoader = getClass().getClassLoader();
File fileObj = new File(classLoader.getResource("request/create-body.json").getFile());
// use try-catch block to convert JSON data into Map
Map<String, Object> createBodyData;
try {
// read JSON data from file using fileObj and map it using ObjectMapper and TypeReference classes
createBodyData = JsonUtility.MAPPER.readValue(
fileObj, new TypeReference<>() {
});
createBody = JsonUtility.MAPPER.convertValue(createBodyData, JsonNode.class);
String contentType = "application/json";
new Expectations() {{
request = new MockHttpServletRequest(); // This line give above error
request.setServerName("localhost");
request.setServerPort(8080);
request.setRequestURI("/api/body");
request.setContent(createBody.binaryValue());
request.setContentType(contentType);
request.setMethod("POST");
request.addHeader("Content-type", contentType);
request.addHeader("Authorization", "Bearer " + accessToken);
}};
responseEntity = bodyController.createBody(JsonUtility.MAPPER.convertValue(createBody, BodyDto.class), request);
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

jakarta.servlet.ServletConnection是在Servlet 6.0中添加的。来自MockHttpServletRequestjavadoc:

从Spring 6.0开始,这组mock是在Servlet 6.0上设计的基线。

如果您使用Maven,您可能需要声明此依赖项:

<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<!-- Mark as provided if the servlet jar is provided by the application server -->
<!-- <scope>provided</scope> -->
</dependency>

您可以使用以下命令检查您的依赖关系:

mvn dependency:tree

相关内容