Why getting the AssumptionViolatedException? Junit 4.8.2 - unit-testing

I'm trying to make Junit tests. I want to start them by asking for a method in the CMS system. Because I'm testing plugins. The problem is that I get this exception and I don't know why. Naah I find that the problem could be that I'm using JUnit 4.8.2, but when I'm running the test in Eclipse everything worked fine. So I can't find the solution. Here is the error:
org.apache.velocity.exception.MethodInvocationException: Invocation of method
'getTest' in class nl.company.cms.three.viewtool.LoginViewTool threw exception
java.lang.NoClassDefFoundError: org/junit/internal/AssumptionViolatedException at
working/2a90929a-3fbf-43e9-9961-4a40279ec907_5c6e0bff-cfeb-44c6-86e2-
a0ba40e7b66c.field[line 1, column 15]
Here is the code of my class and test class:
Class that calls to start the Test:
public String getTest(){
Result r = org.junit.runner.JUnitCore.runClasses(MyTestClass.class);
if(r.getRunCount() > 0){
String s = "Failcount = " + r.getFailureCount() + " // " +
r.getRunCount() + " in " + r.getRunTime() + " ms";
System.out.println(r.getFailures().get(0).getTrace());
System.out.println("Runcount: "+r.getRunCount());
System.out.println("Runtime: "+r.getRunTime());
System.out.println("Ignore count: "+r.getIgnoreCount());
System.out.println("Failure count: "+ r.getFailureCount());
return s;
}
else{
return "Something ging kei verkeerd jonge!";
}
}
Test class:
public class MyTestClass {
#Test
public void testMultiply() {
CustomLoginViewTool tester = new CustomLoginViewTool();
assertEquals("Result", 40, tester.multiply(10, 5));
}
#Test
public void testMultiply1() {
CustomLoginViewTool tester = new CustomLoginViewTool();
assertEquals("Result", 50, tester.multiply(10, 5));
}
#Test
public void testMultiply2() {
CustomLoginViewTool tester = new CustomLoginViewTool();
assertEquals("Result", "ASDF", tester.multiply(10, 5));
}
#Test
public void testMultiply3() {
CustomLoginViewTool tester = new CustomLoginViewTool();
assertEquals("Result", 50, tester.multiply(10, 5));
}
#Test
public void testMultiply4() {
CustomLoginViewTool tester = new CustomLoginViewTool();
assertEquals("Result", 47, tester.multiply(10, 5));
}
#Test
public void testMultiply5() {
CustomLoginViewTool tester = new CustomLoginViewTool();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}

Assumptions are exceptions that JUnit will catch but which won't fail the test. These are for "this test only makes sense if" kind of questions. There is no point to fail Windows-path tests on a Linux system, for example - they can't succeed and failing them will give you an error that you can't fix without disabling the tests.
What I find odd is Velocity and JUnit in a single error message. Why is Velocity running JUnit?
The error means that the classpath isn't set up correctly. So you need to look into the classloader which is used to load the class which contains the method getTest()

The problem was that the CMS system uses JUnit 3.8.2 and the plugin needs JUnit 4.8.2. This caused the error because Java takes the newest version of JUnit and this has not the API of the AssumptionViolatedException.

That class implements a hamcrest class, so make sure you have the hamcrest-core jar on the classpath.

Related

unit testing for aem not covering a condition

im new to unit testing. I am using junit5 for an aem 6.5 application. Im trying to write unit test so that i can migrate to cloud which has a requirement of atleast 50% unit test, thus what im doing now. My code has an init method for the getTags(). My unit test works fine but the jacoco reports a line that is not being covered. Any help would be appreciated to pint me in the right direction.
I have this class:
#Self
private SlingHttpServletRequest request;
#ValueMapValue
private List<String> tags;
#Override
public String getExportedType() {
return RESOURCE_TYPE;
}
#PostConstruct
public void init() {
Resource tagsNode = request.getResource().getChild("tags");
tags = new ArrayList<>();
if (tagsNode!=null) {
for (Resource child : tagsNode.getChildren()) {
TagModel tag = child.adaptTo(TagModel.class);
tags.add(tag.getTag());
}
}
}
public List<String> getTags() {
return this.tags;
}
And i have this unit test for aem
#Test
void testGetTags() {
List<String> expected = new ImmutableList.Builder<String>()
.add("4")
.add("22")
.build();
ctx.currentResource("/content/blog_placeholder");
BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);
List<String> actual = blogPlaceholderModel.getTags();
assertEquals(expected, actual);
}
#Test
void testGetExportedType() {
final String expected = "furniture-row/components/content/blog-placeholder";
ctx.currentResource("/content/blog_placeholder");
BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);
String actual = blogPlaceholderModel.getExportedType();
assertEquals(expected, actual);
}
For some reason my test is not covering the if condition:
what am i missing ? thanks
Your tests are covering this line partially.
You do have a test for the case that (tagsNode != null) == true but not for (tagsNode != null) == false. Therefore, the line is yellow to indicate that not all "branches" of the if statement are covered.

How to write single test runner for classes with different #RunWith()?

I wrote simple method that executes tests in my test classes: DataContainerTest.class, AnotherTest.class.
public static void main(String [] args) throws Exception {
Result result = JUnitCore.runClasses(DataContainerTest.class, AnotherTest.class);
System.out.println(result.getRunCount());
System.out.println("Total number of tests " + result.getRunCount());
System.out.println("Total number of tests failed: " + result.getFailureCount());
for(Failure failures : result.getFailures()){
System.out.println(failures.getMessage());
}
System.out.println(result.wasSuccessful());
}
This method doesn't work for my another class CommandsTest.class, where i'm using annotation #RunWith(PowerMockRunner.class). See output below:
1
Total number of tests 1
Total number of tests failed: 1
No runnable methods
false
Here is the sample of the CommandsTest.class
#RunWith(PowerMockRunner.class)
#PrepareForTest({Helper.class,
UtilsPlatform.class,
SessionManager.class,
DataContainerTest.class,
FieldObserver.class,
android.util.Log.class})
public class CommandsTest {
private static Commands2 commands;
private static License mockedLicense;
private static HSQL hsql;
#BeforeClass
public static void setUpStatic() throws Exception {
commands = new Commands2();
PowerMockito.mockStatic(UtilsPlatform.class);
PowerMockito.when(UtilsPlatform.isTablet()).thenReturn(true);
PowerMockito.mockStatic(android.util.Log.class);
PowerMockito.mockStatic(FieldObserver.class);
PowerMockito.doNothing().when(FieldObserver.class, "put", Mockito.anyInt(),
Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any(Session.class));
hsql = PowerMockito.mock(HSQL.class);
PowerMockito.when(hsql, "OnCaseOpen", Mockito.anyInt(), Mockito.anyInt(),
Mockito.anyInt()).thenReturn(false);
mockedLicense = PowerMockito.mock(License.class);
}
#Before
public void setUp() throws Exception {
PowerMockito.mockStatic(SessionManager.class);
PowerMockito.mockStatic(Helper.class);
PowerMockito.doNothing().when(Helper.class, "writeToFile", Mockito.anyString(),
Mockito.any(SocketException.class));
PowerMockito.when(Helper.class, "getLicense").thenReturn(mockedLicense);
PowerMockito.doNothing().when(Helper.class, "fieldOpened", Mockito.anyString(), Mockito.anyString());
}
#Test
public void sendKeyCombinationEventTest_nullParameters_returnOne(){
Assert.assertEquals(1, commands.sendResponse());
}
#Test
public void sendKeyCombinationEventTest_registredGuisNotNullAndOneIsLocal_returnOne(){
Assert.assertEquals(1, commands.sendKeyCombinationEvent());
}
While pressing run button in AndroidStudio, all tests are passed but my own TestRunner cannot run tests in this class.
The best way to handle classes using #RunWith(PowerMockRunner.class) annotation is just put them into default test source of your android project and then run all tests via gradle test. You don't actually need to write own test runner.

Junit error - No value present or no such element

testclass.java
#Test
public void testgetDictionaryValueListById() {
DictionaryValue dictionaryValue = new DictionaryValue();
dictionaryValue.setId(1);
dictionaryValue.setValueName("Test Dictionary Value");
dictionaryValue.setValueKey("12345678");
dictionaryValue.setStatus("Active");
dictionaryValue.setCreatedOn(new Date());
dictionaryValue.setUpdatedOn(new Date());
Mockito.when(dictionaryValueRepo.findById(1).get()).thenReturn(dictionaryValue);
assertThat(dictionaryService.getDictionaryValueListById(1)).isEqualTo(dictionaryValue);
}
Service.java
public DictionaryValue getDictionaryValueListById(int id) {
return dictionaryValueRepo.findById(id).get();
}
Repo.java
#Repository
public interface DictionaryValueRepo extends JpaRepository<DictionaryValue, Integer> {
}
I am getting no such value present again and again on executing test case in testclass.java. I don't know why? but when I am running my service method from the controller it is working as expected - fetching records from the database but not working in a test case.
Your test should be like this and please check out the naming. You need to Mock the step findId() befor the `get().
#InjectMocks
Service cut;
#Mock
DictionaryValueRepo dictionaryValueRepoMock;
// Can skipped by adding a #RunWith... on Testclass
#Before
public init() {
Mockito.initMocks(this);
}
#Test
public void testgetDictionaryValueListById() {
// Prepare Data
final int testId = 1;
DictionaryValue dictionaryValue = new DictionaryValue();
dictionaryValue.setId(testId);
dictionaryValue.setValueName("Test Dictionary Value");
dictionaryValue.setValueKey("12345678");
dictionaryValue.setStatus("Active");
dictionaryValue.setCreatedOn(new Date());
dictionaryValue.setUpdatedOn(new Date());
// config mocking
Mockito.when(dictionaryValueRepo.findById(testId)).thenReturn(<VALUE>);
Mockito.when(dictionaryValueRepo.findById(testId).get()).thenReturn(dictionaryValue);
// Call yout method for Testing
cut.getDictionaryValueListById(testId);
// verifies (if wanted) + assertions....
}
I concur with LenglBoy, so the right answer should be given to him.
The thing you need to be careful is what "VALUE" means in this line:
Mockito.when(dictionaryValueRepo.findById(testId)).thenReturn(VALUE);
The findById returns an Optional, so that is what you should build and pass to Mockito. Something like this:
Mockito.when(dictionaryValueRepo.findById(testId))
.thenReturn(Optional.ofNullable(dictionaryValue));
And for a scenario where the id does not exists in BD, passing Optional.empty() should be good enough.

Play Framework 2.4.0 unit-testing issue

My problem is as follows:
I am trying to test multiple unit-tests in my controller in a Play Framework 2.4 application. I figured out I need to use a FakeApplication to run the FakeRequests to my controllers in, but for some odd reason the unit-tests work if I start and stop a new FakeApplication. If I start and stop the same FakeApplication, the first unit-test with a FakeRequest works, and the rest dont.
My question:
What am I doing wrong? Why are my unit-tests working if I start and stop a new FakeApplication, and why are they not working if I start and stop the same FakeApplication?
Here is my code snippet:
UnitTest class:
#Test
public void submitTestCorrectInput() {
final String input = CORRECT_INPUT;
final Result result = doCall(input);
assertThat(result.status(), is(equalTo(Http.Status.OK)));
}
#Test
public void submitTestIncorrectInput() {
final String input = INCORRECT_INPUT;
final Result result = doCall(input);
assertThat(result.status(), is(equalTo(Http.Status.NOT_FOUND)));
}
private Result doCall(final String input, final String max, final String filter) {
final Http.RequestBuilder requestBuilder = Helpers.fakeRequest(routes.Application.submit(input));
return route(requestBuilder);
}
Superclass from unittest class:
#Before
public void setUp() {
Play.start(Helpers.fakeApplication().getWrappedApplication());
}
#After
public void tearDown() {
Play.stop(Helpers.fakeApplication().getWrappedApplication());
}

PowerMock + EasyMock unexpected method call

I have a method like this which I want to unit test
public void update(String collectionName, BasicDBObject query, BasicDBObject updateObj){
try{
DBCollection collection = getCollection(collectionName);
collection.update(query, updateObj, true, false);
} catch (MongoException e) {
if (e.getMessage().startsWith("can't call something")) {
refreshConnection(collectionName);
} else {
throw e;
}
}
}
And the test code is as below. I have tried both the methods in the comments in unit test case and currently have commented it.
#Test
public void testUpdate(){
MongoStore store = PowerMock.createStrictPartialMockForAllMethodsExcept(MongoStore.class, "update");
DBCollection collection = PowerMock.createMock(DBCollection.class);
BasicDBObject updateobj = new BasicDBObject("test","shrikar");
String name = "testcoll";
String id = "123";
BasicDBObject query = new BasicDBObject("id",id);
EasyMock.expect(store.getCollection(name)).andReturn(collection);
//EasyMock.expect(collection.update(EasyMock.anyObject(BasicDBObject.class),EasyMock.anyObject(BasicDBObject.class),EasyMock.anyBoolean(),EasyMock.anyBoolean()));
//EasyMock.expect(collection.update(query,updateobj,true,false));
PowerMock.replayAll();
store.update(name,query,updateobj);
EasyMock.expectLastCall().times(1);
PowerMock.verifyAll();
}
In all the cases I keep getting
Unexpected Method call DBCollection.update({"id":"123"},{"test":"shrikar"}, true, false)
What am I missing?
Ok I found out the problem I had forgotten to add Mongo*.class to PrepareForTest
#PrepareForTest({MongoStore.class,MongoOptions.class,Mongo.class, BasicDBObject.class,DBCursor.class,DBObject.class})