How to compare two objects in Junit - junit

I am new to java & Junit. Please help to write Junit test case to test the CargoBO method where Equals & Hashcode functionalities are not implemented.Basically i need to compare 2 objects using Equalbuilder class in junit.
public class CargoBO {
public Cargo cargoDetails(String name,String desc,double length,double width) {
return new Cargo(name,desc,length,width);
}
}
public class CargoJUnit {
Cargo cargo;
#Before
public void createObjectForCargo() {
cargo = new Cargo("audi","des",123.00,234.00);
}
#Test
public void testCargoDetails() {
CargoBO cargoBO = new CargoBO();
//assertTrue(cargo.equals(cargoBO.cargoDetails("audi","des",123.00,234.00)));
Assert.assertEquals(cargo, cargoBO.cargoDetails("audi","des",123.00,234.00));
}
}

Correct test case for your scenario is
#Test
public void testCargoDetails() {
String name = "test name";
String desc = "desc";
double length = 10d;
double width = 100d;
Cargo result = cargoBO.cargoDetails(name, desc, length, width);
Assert.assertEquals(cargo.getName, name);
Assert.assertEquals(cargo.getDesc, desc);
Assert.assertEquals(cargo.getLength, length);
Assert.assertEquals(cargo.getWidth, width);
}
You are testing a method which accepts parameters and calls a constructor passing those parameters.
Your test should be verifying if the given parameters are correctly passed by the method or not.

Related

Unit test for Spring KafkaListener with "Acknowledge" interface as an argument

I'm not expert at unit test but trying to write unit test for :
#KafkaListener(id = "group_id", topics = "topic" )
public AvroObject listen(AvroObject test, Acknowledgment ack)
But no idea how I can make it when there is and interface as an argument. I try this but not sure is it something useful or not make sense as an test :
#InjectMocks
KafkaConsumer kafkaConsumerTest;
#Test
#DisplayName("Assert Valid Consume")
void consumeValidEvent() throws URISyntaxException, IOException, InterruptedException {
// given
AvroObject event = createEvent(); //Create sample object as AvroObject
// when
AvroObject response = kafkaConsumerTest.listen(event, new Acknowledgment() {
#Override
public void acknowledge() {
}
#Override
public void nack(long sleep) {
//do nothing
}
// then
assertNotNull(response);
assertEquals(response.getCode1() ,98765);
assertEquals(response.getCode2() ,123456);
}
I was wondering if you can give me the best approach for this situation! cheers

How to run different tests on a single Document variable which was fetched with Jsoup.connect(string)

I have multiple test cases and I want to use a single Document variable with all of them.
There are more test units which will use this Document.
I had an idea to download the html code, in order to avoid connecting to the site multiple times and taking up server resources, but still I think that it wouldn't be an optional approach to testing.
public class ScrapperTest {
public ScrapperTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
/**
* Test of scrapeManufacturer method, of class Scrapper.
*/
#Test
public void testScrapeManufacturer() {
System.out.println("scrapeManufacturer");
Document html = null;
Scrapper instance = new ScrapperImpl();
String expResult = "";
String result = instance.scrapeManufacturer(html);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
}
/**
* Test of scrapeMinPrice method, of class Scrapper.
*/
#Test
public void testScrapeMinPrice() {
System.out.println("scrapeMinPrice");
Document html = null;
Scrapper instance = new ScrapperImpl();
String expResult = "";
String result = instance.scrapeMinPrice(html);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}

Lifecycle of #After method

I am trying to gather some information after every test method, and would like to analyze the gathered information after the test class completes. So, I have a private member variable, a list which I would like to add to after every test method completes. However, at the end of the day, the member variable always remains null.
Note: My test class implements Callable interface.
Here is my code snippet:
{
private List<String statisticsCollector;
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
this.statisticsCollector = new ArrayList<String>();
}
#Override
public List<String> call() {
log.info("Starting a new thread of execution with Thread# -" + Thread.currentThread().getName());
core.run(this.getClass());
return getStatisticsCollector(); // this is always returing a list of size 0
}
#After
public void gatherSomeStatistics() {
x = x+1;
String sb = new String("Currently executing ----" + x);
log.info("Currently executing ----" + x);
addToStatisticsCollector(sb);
}
#Test
#FileParameters(value = "classpath:folder/testB.json", mapper = MyMapper.class)
public void testB(MarsTestDefinition testDefinition) {
runTests(testDefinition);
}
#Test
#FileParameters(value = "classpath:folder/testA.json", mapper = MyMapper.class)
public void testA(MyDefinition testDefinition) {
runTests(testDefinition);
}
public List<String> getStatisticsCollector() {
return this.statisticsCollector;
}
public void addToStatisticsCollector(String sb) {
this.statisticsCollector.add(sb);
}
}
So, why is it always getting reset, even though I am appending to the list in my #After annotated method?
Any help will be highly appreciated. Thanks
Try with following code, is it working ?
private static List<String> statisticsCollector = new ArrayList<String>();
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
}
public List<String> getStatisticsCollector() {
return statisticsCollector;
}

PageableHandlerMethodArgumentResolver in unit test does not parse sort direction

I have the controller and unit test shown below. The controller returns a sorted list. In the unit test, the sort field is passed correctly; however, the sort direction is not being parsed:
I am following these examples:
Isolated Controller Test can't instantiate Pageable
4. Paging and Sorting
Controller:
#RequestMapping("/telemetry")
public Page<TelemetryMessage> List(Pageable pageable) {
return telemetryMessageRepository.findAll(pageable);
}
Unit Test:
#Before
public void setUp() throws Exception {
mvc = MockMvcBuilders
.standaloneSetup(new TelemetryController(telemetryMessageRepository))
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(new ViewResolver() {
#Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return new MappingJackson2JsonView();
}
})
.build();
// etc.
}
#Test
public void testListReturnsDefault20() throws Exception {
Iterable<TelemetryMessage> expected = telemetryMessageRepository.findAll(new PageRequest(0, 20, Sort.Direction.DESC, "id"));
String json = mapper.writeValueAsString(expected);
MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/telemetry")
.param("sort", "id")
.param("id.dir", "desc")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
String actual = result.getResponse().getContentAsString();
}
Use comma to separate the Property and the Direction, like following:
MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/telemetry")
.param("sort", "id,desc")
//.param("id.dir", "desc")

Junit testing for a class with strings

//DOC Datatype Constants
public enum DocDatatype {
PROFILE("Profile"),
SUPPORT_DETAIL("SupportDetail"),
MISC_PAGE("MiscPage"),
String name;
DocDatatype(String name) {
this.name = name;
}
public String getName() {
return name;
}
// the identifierMethod
public String toString() {
return name;
}
// the valueOfMethod
public static DocDatatype fromString(String value) {
for (DocDatatype type : DocDatatype.values()) {
if (type.getName().equals(value))
return type;
}
throw new java.lang.IllegalArgumentException(value
+ " is Not valid dmDataType");
}
}
I have written the junit test case in this way. Whether it is right way to write or wrong way...?
public class DocDatatypeTest {
private static final Log logger = LogFactory
.getLog(TreeConstantTest.class);
#Test
public void testDocDatatypeFromName()
{
DocDatatype d= DocDatatype.fromString("Profile");
assertTrue((d.toString().compareToIgnoreCase("PROFILE") == 0));
}
#Test
public void testDocDatatypeFromName1()
{
DocDatatype d = DocDatatype.fromString("SupportDetail");
assertTrue((d.toString().compareToIgnoreCase("SUPPORT_DETAIL") == 0 ));
}
}
}
A few things here:
Remove the logger from the test. A test should pass or fail, no need for logging
Don't use assertTrue for this. If the test fails it will give you no information about /why/ it failed.
I would change this to
#Test
public void testDocDatatypeFromName()
{
DocDatatype actualDocType = DocDatatype.fromString("Profile");
assertSame(DocDataType.PROFILE, actualDocType);
}
If you really want to assert that value of the toString then do this
#Test
public void testDocDatatypeFromName()
{
DocDatatype d= DocDatatype.fromString("Profile");
assertEquals("Profile", d.toString());
}
You're missing tests for when the lookup doesn't match anything
I wouldn't even write these tests as I see them adding no value whatsoever. The code that uses the enums should have the tests, not these.
Your tests are named very badly. There's no need to start a test with test and the fact you add a "1" to the end of the second test should tell you something. Test names should focus on action and behaviour. If you want to read more about this, get the December issue of JAX Magazine which has a snippet about naming from my forthcoming book about testing.