如何使用JUnit MockMVC测试Hystrix-Fallback

时间:2018-11-29 06:51:06

标签: spring spring-mvc spring-boot-test spring-mvc-test

我需要有关jUnit测试的帮助,我的结果是json,并且我需要测试Fallback方法,该方法支持在Service的Update方法中构建的RuntimeException。测试不会进行回退。

Controller.java

private static final Score defaultScore = new Score("Team1", "Team2", 1, 1);

@PutMapping(path = "")
@HystrixCommand(fallbackMethod = "updateScoreFallback")
public ResponseEntity<Score> updateScore(@RequestBody Score score) {
    Score s = scoreService.updateScore(score);
    return new ResponseEntity<>(s, headers, HttpStatus.OK);
}

public ResponseEntity<Score> updateScoreFallback(Score score) {
    return new ResponseEntity<>(defaultScore, headers, HttpStatus.SERVICE_UNAVAILABLE);
}

我的测试

@NoArgsConstructor
@RunWith(SpringRunner.class)
@WebMvcTest(value = ScoreController.class, secure = false)
public class ScoreControllerExceptionTests {

@Autowired
private MockMvc mockMvc;

@MockBean
private ScoreService ScoreService;

private ScoreController ScoreController;

private static final String basePath = "/v1/score";

private static final Score Score = new Score("Team1", "Team2", 1, 1);

private static final String mockScoreJson = "{\"id\":0,\"team_name1\":\"Team1\",\"team_name2\":\"Team2\",\"score_team1\":1,\"score_team2\":1}";

private static final List<Score> scoreList = Collections.singletonList(score);

private static final String mockScoreListJson = "[" + mockScoreJson + "]";



@Before
public void setUp() {
    ScoreRepo scoreRepo = new ScoreRepoExceptionStub();
    scoreService = new ScoreServiceImpl(scoreRepo);
    scoreController = new ScoreController(scoreService);
    mockMvc = MockMvcBuilders.standaloneSetup(scoreController).build();
}

@Test
public void updateScoreControllerException() throws Exception{

    String result = mockMvc.perform(MockMvcRequestBuilders
            .put(basePath)
            .accept(MediaType.APPLICATION_JSON)
            .content(mockScoreJson)
            .contentType(MediaType.APPLICATION_JSON))
            .andReturn()
            .getResponse()
            .getContentAsString();               
    Assert.assertEquals(mockScoreJson, result, true);
}

....

感谢帮助

0 个答案:

没有答案