Spring Boot集成测试Mock方法返回null

时间:2019-03-06 04:37:44

标签: java spring spring-boot mockito

我用ControllerServiceBusiness类编写了简单的spring boot应用程序,但是在进行集成测试时,Service的模拟方法返回了空值

MockMainController

@RestController
public class MockMainController {

@Autowired
private MockBusiness mockBusiness;

@GetMapping("request")
public MockOutput mockRequest() {
    return mockBusiness.businessLogic(new MockInput());

      }

  }

MockBusiness

@Service
public class MockBusiness {

@Autowired
private MockService mockService;

public MockOutput businessLogic(MockInput input) {
    return mockService.serviceLogic(input);
    }
}

MockService

@Service
public class MockService {

@Autowired
private MockUtil mockUtil;

public MockOutput serviceLogic(MockInput input) {

    mockUtil.exchange(UriComponentsBuilder.fromUriString(" "), HttpMethod.GET, HttpEntity.EMPTY,
            new ParameterizedTypeReference<MockOutput>() {
            });
    return new MockOutput();

     }

 }

我正在尝试使用MockService在应用程序上下文中模拟@MockBean bean

MockControllerTest

@SpringBootTest
@ActiveProfiles("test")
@Profile("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockControllerTest {

@Autowired
private MockMainController mockMainController;

@MockBean
private MockService mockService;

@Test
public void controllerTest() {
    MockOutput output = mockMainController.mockRequest();
    given(this.mockService.serviceLogic(ArgumentMatchers.any(MockInput.class)))
            .willReturn(new MockOutput("hello", "success"));
    System.out.println(output);    //null
     }

 }

在测试方法中,我使用@MockBean创建了模拟服务bean,这里没有任何错误,但是System.out.println(output);打印了null

1 个答案:

答案 0 :(得分:2)

由于测试方法中的语句顺序错误,您得到null。您首先调用控制器方法,然后获得默认值@MockBean中的内容,本例中为null。交换声明:

MockOutput output = mockMainController.mockRequest(); 

given(this.mockService.serviceLogic(ArgumentMatchers.any(MockInput.class)))
        .willReturn(new MockOutput("hello", "success")); 

您将获得预期的结果。