春季引导覆盖日期

时间:2018-10-22 15:17:53

标签: spring-mvc spring-boot integration-testing

我正在编写REST API的集成测试。我在测试时遇到问题 MyService类中validateDate的逻辑。我想模拟currentDate()方法MyService类,以编写不同的测试方案。如何在Spring Boot中实现这一目标?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerTest {

    TestRestTemplate restTemplate = new TestRestTemplate();

    @LocalServerPort
    private int port;   

    //@MockBean
    //MyService service;

    @Test
    public void testRetrieveStudentCourse() {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/validatedate"),
                HttpMethod.GET, entity, String.class);

        String expected = "true";

        assertEquals(expected, response.getBody(), false);
    }

    private String createURLWithPort(String uri) {
        return "http://localhost:" + port + uri;
    }





import java.util.Date;

import org.springframework.stereotype.Service;

public interface IMyService {

    public boolean validateDate(Date date);
}

@Service
public class MyService implements IMyService{

    public boolean validateDate(Date date) {
        if(currentDate().before(date)) {
            return true;
        }
        return false;
    }

    private Date currentDate() {
        return new Date();
    }
}


import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @Autowired
    IMyService service;

    @GetMapping(value = "/validatedate", produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean validateDate() {
        // date object will be retrieved.
        Date date = somedate;
        service.validateDate(date);
    }
}



Mockito.when(myservice.currentDate()).thenReturn(null);

         doReturn(null).when(myservice.currentDate());

1 个答案:

答案 0 :(得分:0)

import static org.mockito.Mockito.when;
........................
public class MyControllerTest {
    @Mock
    IMyService service

    .........................................
    @Test
    public void myTest(){
        when(service.validateDate(date)).thenReturn(false);
    ......... do test .............................................
    }
}