Springboot测试问题:Mockito返回空对象

时间:2019-07-11 19:35:20

标签: spring spring-boot spring-mvc mockito

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

谢谢。

1 个答案:

答案 0 :(得分:0)

这有助于我理解:Mockito - thenReturn always returns null object

我将Mockito.when部分更改为:

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

成功了