How can I test the Hystrix-Fallback with JUnit MockMVC

400 Views Asked by At

I need help with the jUnit testing, my result is json, and I need to test the Fallback method, that I bacome the RuntimeException that I build in the Update method in the Service. The test dont go to the fallback.

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);
}

My Test

@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);
}

....

Thanks for the helps

0

There are 0 best solutions below