我正在尝试构建一个使用 gradle 作为构建工具和 openjdk-11 的原型。这个原型将在 springboot 框架上构建一个 rest-api。
我的模块在 rest-api 调用和返回预期结果时工作正常。但是,由于我现在正在尝试为其余 API 编写测试,测试失败,因为 Mockito 返回空对象。希望能深入了解我应该如何为此 rest-api 编写测试或如何修复它。
我的控制器:
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@Autowired
GreetingService service;
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return service.getGreetings(0L, String.format(template, name));
}
}
服务内容:
@Service
public class GreetingService {
public Greeting getGreetings() {
return new Greeting(1L, "Hello World");
}
public Greeting getGreetings(Long id, String name) {
return new Greeting(id, name);
}
}
模型:
@Builder
@Data
@RequiredArgsConstructor
@JsonDeserialize(builder = Greeting.class)
public class Greeting {
@NonNull
private Long id;
@NonNull
private String content;
}
主类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我通过以下方式执行了这个:
gradle bootrun
然后从浏览器中,尝试:
http://localhost:8080/greeting
然后返回:
{"id":0,"content":"Hello, World!"}
再次尝试:
http://localhost:8080/greeting?name=Patty
然后返回:
{"id":0,"content":"Hello, Patty!"}
现在,我正在尝试编写测试以编程方式验证类似于上述调用的 api 调用。所以我尝试了:
@RunWith(MockitoJUnitRunner.class)
public class GreetingControllerTest {
private MockMvc mockMvc;
@Mock
private GreetingService service;
@InjectMocks
private GreetingController controller
@Test
public void testGreeting() throws Exception {
Greeting greeting = new Greeting(0L,"Patty!");
String expectedResponse = "{"id":0,"content":"Hello, Patty!"}";
//JacksonTester.initFields(this, new ObjectMapper());
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.build();
Mockito.when(service.getGreetings(0L,"Patty")).thenReturn(greeting);
MockHttpServletResponse response = mockMvc
.perform(get("/greeting?name=Patty")
.contentType(MediaType.ALL))
.andReturn()
.getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(expectedResponse)
}
}
错误消息是:
org.junit.ComparisonFailure:
Expected :"{"id":0,"content":"Hello, Patty!"}"
Actual :""
从此行失败:
assertThat(response.getContentAsString()).isEqualTo(expectedResponse)
提前谢谢。
这有助于我理解: Mockito - thenReturn 总是返回空对象
我将 Mockito.when 部分更改为:
Mockito.when(service.getGreetings(Mockito.anyLong(),Mockito.anyString())).thenReturn(greeting);
它奏效了