Can anyone suggest me how to write JUnit for the below class:
@Controller
@RequestMapping(value = "/cutdata", consumes = "TEXT/XML")
public class CustController
{
Logger LOG = Logger.getLogger(CustController.class);
@Autowired
CustService custService;
@Autowired
MarCusService marCustService;
@Resource(name = "CustValidator")
private CusValidator validator;
@Resource(name = "cmsSiteService")
private CMSSiteService cmsSiteService;
protected CMSSiteService getCmsSiteService()
{
return cmsSiteService;
}
@RequestMapping(value = "/methodcall", method = RequestMethod.PUT)
public @ResponseBody ResponseEntity<?> methodCall(@RequestBody final CustDTO data)
throws WebServicesException
{
String statusCode = null;
try {
if (data.getGroup() != null && !data.getGroup().equals(String.valueOf(GroupEnum.ALL))) {
validator.validate(data);
}
} catch (WebServicesException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.OK);
}
try
{
final CMSSiteModel site = cmsSiteService.getCurrentSite();
String currentSiteId=site.getUid() !=null ? site.getUid():"";
if(StringUtils.contains(currentSiteId,Config.getParameter("****.siteuid")))
{
statusCode = marCustService.processData(data);
}
else
{
statusCode = custService.processData1(data);
}
final String[] message = statusCode.split(":");
final String code = message[0];
final String statusMessage = message[1];
if (code.equalsIgnoreCase("200"))
{
return new ResponseEntity<>(statusMessage, HttpStatus.CREATED);
}
else if (code.equalsIgnoreCase("400"))
{
return new ResponseEntity<>(statusMessage, HttpStatus.BAD_REQUEST);
}
}
catch (final Exception e)
{
LOG.error("log ::" + e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I'm new in writing JUnit Test case, i need help like how to write or how to start JUnit.
Basically, you need to make use of the Spring context to test Controller classes.
One example would be something like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void shouldTestMethodCall() {
mockMvc.perform(put("/methodcall"))
.andExpect(status.isOk());
}
}
From this test you can expand the testing to whatever your flows are. If you need more references, you can check Spring's documentation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With