0

我正在尝试构建一个使用 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)

提前致谢。

4

1 回答 1

0

这帮助我理解:Mockito - thenReturn always return null object

我将 Mockito.when 部分更改为:

Mockito.when(service.getGreetings(Mockito.anyLong(),Mockito.anyString())).thenReturn(greeting);

它奏效了

于 2019-07-12T16:29:36.433 回答