Tests should have good coverage of the types of exceptions and errors that this class can throw, and it should have good coverage of the defective statements in the constructor method for CalculatePrimesMother.
The method for which three Junit test case needed is as below:
public CalculatePrimesMother(int numWorkers, int queueLength, int maxPrime,
boolean verbose) {
this.numWorkers = numWorkers;
// Instantiate 3 queues, for thread-safe communication with workers
Candidate = new ArrayBlockingQueue<Integer>(queueLength);
Prime = new ArrayBlockingQueue<Integer>(queueLength);
Composite = new ArrayBlockingQueue<Integer>(queueLength);
this.maxPrime = maxPrime;
this.sqrtMaxPrime = (int) Math.sqrt(maxPrime);
primeFactors = new int[sqrtMaxPrime];
this.verbose = verbose;
}
I tried and created some test case but not able to get full coverage can anyone help me?
public class CalculatePrimesMotherTest extends TestCase {
public CalculatePrimesMotherTest(String name) {
super(name);
}
private CalculatePrimesMother testMother;
#Test
public final void testCalculatePrimesMotherNegativequeueLength() {
try {
testMother = new CalculatePrimesMother(4, -12, 908, false);
} catch (Exception e) {
e.printStackTrace();
}
}
#Test
public final void testCalculatePrimesMotherMinusOne() {
try {
testMother = new CalculatePrimesMother(8, 12, 0, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
What coverage do you get? There are no if tests in your ctor, so a single call should exercise all the code that I see.
You're writing too much code. The setUp and tearDown and test constructor methods are all unnecessary. Remove them.
You don't need the try/catch blocks in the other tests. Remove those, too. You want an exception to trigger a test failure. Catching will hide the error.
Related
Trying to test repository method, but my test fails with following "Wanted but not invoked: cellphonesDao.deleteAllCellphones();"
Here is repo method:
#Override
public Single<Cellphone[]> getCellphones() {
Single<CellPhoneEntity[]> remoteCellphones =
networkModule.productApi()
.getCellPhones()
.onErrorResumeNext(cellphonesDao.getAllCellphones()); // todo return value if true
Single<CellPhoneEntity[]> localCellphones = cellphonesDao.getAllCellphones();
return Single.zip(remoteCellphones, localCellphones, (remote, local) -> {
if (!Arrays.equals(remote, local)) {
cellphonesDao.deleteAllCellphones();
for (CellPhoneEntity cellPhoneEntity : remote) {
cellphonesDao.insertCellphone(cellPhoneEntity);
}
}
return mapper.toCellphones(remote);
});
}
Main porpuse is to test repo method in correct way. Guess the way I chose is not good.
Here is test implementation:
class CellPhoneRepositoryImplTest {
NetworkModule networkModule;
CellphonesDao cellphonesDao;
CellphoneMapper cellphoneMapper;
CellPhoneRepositoryImpl cellPhoneRepository;
ProductAPI productAPI;
#BeforeEach
void setUp() {
networkModule = Mockito.mock(NetworkModule.class);
cellphonesDao = Mockito.mock(CellphonesDao.class);
productAPI = Mockito.mock(ProductAPI.class);
cellphoneMapper = new CellphoneMapper();
cellPhoneRepository = Mockito.spy(new CellPhoneRepositoryImpl(
networkModule,
cellphonesDao,
cellphoneMapper
));
}
#Test
void whenRemoteDataAreDifferentFromLocalDbIsUpdated() {
int numberOfCellphones = 5;
CellPhoneEntity[] remoteCellphones = DummyCellphoneEntityFactory.generateCellphones(numberOfCellphones);
CellPhoneEntity[] localCellphones = DummyCellphoneEntityFactory.generateCellphones(numberOfCellphones);
Mockito.when(networkModule.productApi()).thenReturn(productAPI);
Mockito.when(networkModule.productApi().getCellPhones()).thenReturn(wrapWithSingle(remoteCellphones));
// Mockito.when(networkModule.productApi().getCellPhones().onErrorResumeNext(cellphonesDao.getAllCellphones())).thenReturn(wrapWithSingle(remoteCellphones));
Mockito.when(cellphonesDao.getAllCellphones()).thenReturn(wrapWithSingle(localCellphones));
Mockito.doNothing().when(cellphonesDao).deleteAllCellphones();
cellPhoneRepository.getCellphones();
Mockito.verify(cellphonesDao, Mockito.times(1))
.deleteAllCellphones();
}
private Single<CellPhoneEntity[]> wrapWithSingle(CellPhoneEntity[] cellphones) {
return Single.just(cellphones);
}
}
I will be glad for any suggestion)
The code inside the returned Single isn't executed immediately, but your verifications are. Try calling cellPhoneRepository.getCellphones().blockingGet() instead of just cellPhoneRepository.getCellphones(). The blockingGet() should make your test wait until the Single is done executing.
I am trying to create extent report version v4.0.9 but unable to do so.
Below code I have written to setUp class which has all before method and aftermethos and the same class is extented to Utilities class where I am performing tests.
Here is code for setUp class
public class AIG_SetUp {
protected static ExtentLoggerReporter logger;
protected static ExtentReports extent;
protected static ExtentTest log;
#BeforeTest(alwaysRun = true)
public void starttest() {
logger = new ExtentLoggerReporter(System.getProperty("user.dir"));
extent = new ExtentReports();
extent.attachReporter(logger);
System.err.close(); // written to remove JAVA 9 incompatibility.. continued below
System.setErr(System.out); // continue.. and remove the warnings
extent.setSystemInfo("User Name" , "Sobhit");
}
#AfterMethod(alwaysRun = true)
public void endReport(ITestResult result) {
try {
if (result.getStatus() == ITestResult.FAILURE) {
log.log(Status.FAIL , "Test cases Failed" + result.getName());
log.log(Status.FAIL , "Test cases Failed" + result.getThrowable());
} else if (result.getStatus() == ITestResult.SKIP) {
log.log(Status.SKIP , "Test case skipped is" + result.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#AfterTest(alwaysRun = true)
public void endReport() {
extent.flush();
}
}
And here is the utilities class which is extented to above class.
public class UtilitiesOps extends AIG_SetUp {
#Test(groups = {"Core-Smoke"}, description = "List all media types")
public void Verify_List_all_media_types() {
extent.attachReporter(logger);
extent = new ExtentReports();
log = extent.createTest("List all media types");
log.assignCategory("Utilities Operations");
}
Couple of important points to mention
Now I am not getting error, before I was getting null pointer exception but now no error.
Also Code runs fine but not generating the extent report.
If I put everything in one class with no before test and stuff, able to create the report. Not sure why is going wrong.
I really appreciate your help.
I got answer for this after reading about it.
basically I was doing the beforetest without static variables where as it has to be statically intiated because of other global variables.
The below code fixed my issues.
#BeforeTest(alwaysRun = true)
public static void starttest() {
logger = new ExtentLoggerReporter(System.getProperty("user.dir"));
extent = new ExtentReports();
extent.attachReporter(logger);
System.err.close(); // written to remove JAVA 9 incompatibility.. continued below
System.setErr(System.out); // continue.. and remove the warnings
extent.setSystemInfo("User Name" , "Sobhit");
}
I have a method called doParallelThings:
public Dummy doParallelThings(Map<String, String> mapp) throws Exception {
Dummy dummy = new Dummy();
CompletableFuture<Ans1> one = firstService.getOne(mapp.get("some1"), mapp);
CompletableFuture<Ans2> two = secondService.getTwo(headersMap.get("some2"), mapp);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(one, two);
try {
combinedFuture.get();
dummy.setOne(one.get());
dummy.setTwp(two.get());
} catch (Throwable e) {
}
return dummy;
}
Code works fine but when I'm trying to test it,
combinedFuture.get(); goes to infinite loop.
Unit test is as below:
#Mock
private CompletableFuture<Void> ans;
#Test
public void testDoParallelThings() throws Exception {
PowerMockito.mockStatic(CompletableFuture.class);
PowerMockito.when(CompletableFuture.allOf(any())).thenReturn(ans);
when(ans.get()).thenReturn(null);
Dummy dummy = dummyService. doParallelThings(mockMap);
assertNotNull(dummy);
}
I have also added #RunWith(PowerMockRunner.class)
#PrepareForTest({CompletableFuture.class}) above the test class.
What am I missing?
when(firstService.getOne(any(), any())).thenReturn(CompletableFuture.completedFuture(mockOne));
solved my problem
For regression testing (not unit testing), where we have elaborate scenarios written in TestNG, is there a proper place the Assert checks should be done? Does it matter or not if it's in the test case, or in a calling method? For example:
This test case calls a validation method that contains the asserts:
#Test
public void test1() {
validateResponse();
}
public void validateResponse() {
Assert.assertEquals(a, "123");
Assert.assertEquals(b, "455");
Assert.assertEquals(c, "5678");
Assert.assertEquals(d, "3333");
}
This test case asserts based on the return value of the verification method:
#Test
public void test1() {
Assert.assertTrue(validateResponse());
}
public boolean void validateResponse() throws Exception {
try {
if (!a.equals("123")) throw new Exception();
if (!b.equals("455")) throw new Exception();
if (!c.equals("5678")) throw new Exception();
if (!d.equals("3333")) throw new Exception();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Your assert should be as specific and granular as possible to help the developer quickly identify the problem. e.g.
#Test
public void testResponseFields(){
// create response to be tested
// JUnit style
Assert.assertEquals("Response 'alpha' should be '123'", 123, response.getAlpha());
// TestNG style
Assert.assertEquals(response.getAlpha(), 123, "Response 'alpha' should be '123'");
}
Once you set a failure message in the Assert.assertXX call, it becomes more of a moot point as to where the Assert is called as you will have a message explaining the problem and a stack trace to see where and when it failed.
I am writing a test for already built java class function. I am writing tests using Testng and Mockito and have a Data Provider.
This is my Test
#Test(dataProvider = "myProvider", dataProviderClass = StaticDataProvider.class,
expectedExceptions = SomeException.class)
public void myControllerTest(String argument) throws Exception {
// Mocked object bussiness\
Boolean resultantObject = business.getList(argument);
Assert.assertTrue(resultantObject);
}
This is my Controller which I want to test
public Boolean controller(String argument) {
if(argument != null) {
throw new someException();
} else {
System.out.println("Sucess");
return true;
}
}
This is my Data Providor
#DataProvider(name = "myProvider")
public static Object[][] getDirectoryList() throws Exception {
Object[][] result = null;
// case1 throws SomeException
String testData1 = null;
// case2 don't throw exception
String testData2 = "String";
result = new Object[][] { { testData1 }, { testData2 } };
return result;
}
The problem here I am facing is, I don't want to create another test just to test both buggy and non buggy code and complete my test coverage using a single test case. But when I put Expected Exception on top, it fails on correct code, and when I dont, it fails on buggy code.
NOTE: This is example code and may not work, this is just to take an idea of scenario I am working on and what I am expecting.
Even if you ignore the "one test, one assertion" purist perspective, I think most people agree you should split tests that involve error conditions from tests that prove normal behaviour.
If you want to test multiple error conditions within one test (or if you're really keen on continuing with your plan), you can use this pattern:
try {
// something that should cause an exception
fail("Exception expected");
} catch (ExactlyTheRightException e) {
// ignored
}