模擬物件似乎不起作用,正在呼叫實際函式。
我的控制器類如下:-
@RestController
public class A {
@PostMapping(path = "/api/methods", consumes = "application/json", produces = "application/json")
public static ResponseEntity<Object> controllerFunction(@Valid @RequestBody String request,
@RequestHeader(value = "header-content") String header_content) {
JSONObject response = B.getAns(request);
return ResponseEntity.status(HttpStatus.OK).body(response.toString());
}
}
我的B類如下:-
@Service
public class B {
private static C client;
@Autowired
private C beanClient;
@PostConstruct
public void init() {
B.client = beanClient;
}
public static JSONObject getAns(String request) {
// This is the line that I intend to mock but gets ignored. It goes into the function search instead.
JSONObject resp = client.search(searchRequest, requestHeaderOptions); // assume that these two variables passed as arguments are not null and have some content.
// searchRequest is of type SearchRequest
// requestHeaderOptions is of type RequestOptions
return resp;
}
}
這是我的測驗課:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {
ControllerApplication.class, A.class, B.class, C.class
})
@ActiveProfiles("test")
public class ProjectTest {
@Mock
private C client;
@InjectMocks
A a;
private MockMvc mockMvc;
@BeforeSuite
public void setup() {
// I have tried both MockitoAnnotations.initMocks and openMocks. Both don't work
MockitoAnnotations.openMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(a).build();
}
@Test(enabled = true)
public void testing() throws Exception {
JSONObject obj = new JSONObject() // assume this object is not null
// This statement doesn't seem to work
doReturn(obj).when(client).search(any(SearchRequest.Class), any(RequestOptions.Class));
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/methods")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.header("header-content", "something")
.content("someData");
mockMvc.perform(mockRequest)
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(jsonResponse));
}
}
如果您注意到我在 B 類中創建了 C 類的靜態變數。這是程式結構本身的一部分,不能更改。
是否可以模擬client.search給定此代碼的函式?
uj5u.com熱心網友回復:
解決問題的一種快速方法是直接模擬B和存根B.getAns。
為了模擬靜態 B,您應該mockito-inline在 pom.xml 中添加依賴項:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
你可以Mockito.mockStatic這樣使用:
try (MockedStatic<B> mockedB = Mockito.mockStatic(B.class)) {
mockedB.when(() -> B.getAns(anyString())).thenReturn(obj);
// ...
}
因此,您的測驗代碼將是:
@Test(enabled = true)
public void testing() throws Exception {
try (MockedStatic<B> mockedB = Mockito.mockStatic(B.class)) {
JSONObject obj = new JSONObject() // assume this object is not null
mockedB.when(() -> B.getAns(anyString())).thenReturn(obj);
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/methods")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.header("header-content", "something")
.content("someData");
mockMvc.perform(mockRequest)
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(jsonResponse));
}
}
請注意,當您使用 時MockedStatic,您最好使用try-with-resources模式并像上面一樣在此范圍內進行測驗。
閱讀有關 mockStatic 的更多資訊:https ://www.baeldung.com/mockito-mock-static-methods
uj5u.com熱心網友回復:
通過在除錯模式下運行測驗,我能夠找出問題所在。
我發現@PostConstruct我的 B 類中的函式在我的測驗函式之前被呼叫。因此,B 類創建了自己的beanClient物件,與我的測驗類中的模擬物件不同。這就是為什么它進入函式而不是模擬它的原因。
我能夠通過像這樣更改 B 類來解決它:-
@Service
public class B{
@Autowired
private C client;
public JSONObject getAns(String request){
// This is the line that I intend to mock but gets ignored. It goes into the function search instead.
JSONObject resp =client.search(searchRequest,requestHeaderOptions); // assume that these two variables passed as arguments are not null and have some content.
// searchRequest is of type SearchRequest
// requestHeaderOptions is of type RequestOptions
return resp;
}
我不得不將其更改為非靜態函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478949.html
上一篇:如何將值傳遞給沒有引數的方法?
