Adding a #Test method dynamically to junit test class - junit

We have a text file where a list of search query and the expected result is given. Such as,
Search Result
a:120 result1
b:220 result2
.....
.....
Now, we need to write a JUnit (heavily used in our daily build) test class, where each of the row will represent one #Test method. So by that, we know, which search case failed (UI).
We already have a solution, where we have one #Test method only, and we have log to check which case passed or failed.
But, we are trying to achieve per case represented as a junit method. Is it really possible, to dynamically create a #Test method to JUnit architecture.
Our, #Test method is same for every search case. That means, we just want to pass a different parameter every time.
I have come up with a JUnit3 solution to my problem. Need help to translate it to Junit4.
public static Test suite()
{
TestSuite suite = new TestSuite();
for ( int i = 1; i <= 5; i++ ) {
final int j = i;
suite.addTest(
new Test1( "testQuery" + i ) {
protected void runTest()
{
try {
testQuery( j );
} catch ( MalformedURLException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( SolrServerException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
}
return suite;
}

In JUnit 4 there is a concept called "Parameterized Test" that is used for exactly this.
I don't fully understand your test above, but this should give you a hint:
#RunWith(Parameterized.class)
public class ParameterizedTest {
private String query;
private String expectedResult;
public ParameterizedTest(String query, String expectedResult) {
this.query = datum;
this.expectedResult = expectedResult;
}
#Parameters
public static Collection<Object[]> generateData() {
Object[][] data = {
{ "a:120", "result1" },
{ "b:220", "result2" },
};
return Arrays.asList(data);
}
#Test
public void checkQueryResult() {
System.out.println("Checking that the resutl for query " + query + " is " + expectedResult);
// ...
}
}

Related

JUnit Mockito: Testing a Static Method and Calling Another Stubbed Static Method Inside Not Working

class A {
public static int f1() {
return 1;
}
public static int f2() {
return A.f1();
}
}
class ATest {
#Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class)) {
aStatic.when(A::f1).thenReturn(2);
int ret = A.f2(); // getting 0 here
assertEquals(ret, 2);
} catch(Exception e) {
}
}
}
In the testF2 I want to test static function A::f2().
And it internally calls another static function A::f1().
I did stub A::f1() to return 2 using "MockedStatic" and "when" way.
But it's not working, it's returning 0.
How to solve it?
I think you miss to specify a mock behavior:
class ATest {
#Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class)) {
aStatic.when(A::f1).thenReturn(2);
aStatic.when(A::f2).thenReturn(A.f1()); // <- added this
int ret = A.f2(); // getting 0 here
Assertions.assertEquals(ret, 2);
} catch (Exception e) {
}
}
}
by telling the mock what to do when A.f2() is invoked, test runs fine.
Update:
Mocks do what you tell them, if you don't tell what to do when a method is invoked they do nothing, that's why you have to mock f2 too.
You want to test A, then mock it is not your friend. I normally use a Mockito.spy() to partially mock my subject under test .You want to mock f1 but test f2, I don't think spy applies here because there is no instance to spy..
I suggest you to rearrange A avoiding static methods if possible or using parameters you can mock.
When you mock a class with static methods, all static methods are mocked. If you only want to mock the behavior of only 1 method, you have to add Mockito.CALLS_REAL_METHODS argument to Mockito.mockStatic() as you can see in the following example.
#Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class, Mockito.CALLS_REAL_METHODS)) {
aStatic.when(A::f1).thenReturn(2);
int ret = A.f2(); // getting 2 here
Assert.assertEquals(2, ret); // (expected, result)
} catch(Exception e) {
}
}
This way only the f1 method invocation is mocked but f2 invocation calls the real code.

Spring WebFlux; unit testing exception thrown in Mono.map()

I have some code that returns Mono<List<UserObject>>. The first thing I want to do is check the List is not empty, and if it is, throw a NoUsersFoundException. My code looks like this:
IUserDao.java
Mono<List<UserAccount>> getUserProfiles(final Set<UserQueryFilter> filters,
final Set<String> attributes);
GetUserAccount.java
public Mono<UserAccount> doGetUserAccount() {
return userDao.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
throw new NoUsersFoundException();
}
return list;
})
.map(this::removePermissions)
.map(this::removeDuplicates);
}
I want to write a unit test that will test that the NoUsersFoundException is thrown when userDao.getUserProfiles(filters, attributes) returns an empty list. When I use Mockito#when with a .thenReturn(), the test will, as expected, return immediately once userDao.getUserProfiles(...) is called without continuing the flow into the .map() where the list is checked and exception thrown.
#Mock
private IUserDao userDao;
private UserPolicies userPolicies;
#BeforeEach
public void init() {
userPolicies = new UserPolicies(Set.of("XYZ", USER_AFF, "123"),
Set.of(TestUserConstants.ID, TestUserConstants.SUBSCRIPTION_LEVEL));
}
#Test
void shouldThrowExceptionIfNoUsersFound() {
final Set<UserFilter> filters = new UserFilterBuilder().withId(ID)
.withSubscription(PREMIUM)
.build();
when(userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenReturn(Mono.just(Collections.emptyList()));
testClass = new GetUserAccount(userDao,
userPolicies,
filters,
userPolicies.getUserAttributeIds());
assertThatThrownBy(() -> testClass.doGetUserAccount()).isInstanceOf(NoUsersFoundException.class);
}
I have tried .thenAnswer() but it essentially does the same thing as the method called is not a void:
userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenAnswer((Answer<Mono<List>>) invocationOnMock -> Mono.just(Collections.emptyList()));
I can't see how using reactor.test.StepVerifier would work for this case.
i dont really understand what you are asking for, but we commonly dont "throw" exceptions in reactor. We return a Mono#error downstream, and different operators will react accordingly as the error travels downstream.
public Mono<List<Foobar> fooBar(filters, attributes) {
return daoObject.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
// Return a mono#error
return Mono.error( ... );
}
return list;
})
}
And then test using the step verifier. With either expectNext or expectError.
// Happy case
StepVerifier.create(
fooBar(filters, attributes))
.expectNext( ... )
.verify();
// Sad case
StepVerifier.create(
fooBar(filters, attributes))
.expectError( ... )
.verify();

Assert null is not working as actual method changes the value

I am trying to write a Junit for a piece of code for asserting the value as null. But the value is changing on the actual call.
Main Class Code
#Activate
public void activate(ComponentContext context)
{
myNotificationSubscriber = NotificationSubscriber.newInstance(myGlobalTableNotificationService,
NotificationType.ENTITIES,
this);
setWantedSubscriptionStatus();
LOG.debug("Activating {} service", getClass().getName());
try
{
applyConfigUpdate(context, IS_ACTIVATION);
}
catch (ServiceNotAvailableException e)
{
String instanceNameWithException = COUNTER_INSTANCE_COBA.concat("-")
.concat(String.valueOf(e.getResponseCode().getResponseCode()))
.concat(e.getClass().getSimpleName());
myCounterregistrator.get()
.incrementCounter(Counter.DATAACCESS_COBA_RESPONSE_UNSUCCESSFUL.getCounterInstance(instanceNameWithException));
LOG.debug("Can not activate Component :{}", e.getMessage());
}
LOG.info("COBA Cache state is {}", myCacheState);
}
private GlobalTableRetriever getGlobalTableRetrieverer() throws ServiceNotAvailableException
{
GlobalTableRetriever tableFetcher = myGlobalTableRetriever.get();
if (tableFetcher == null)
{
throw new ServiceNotAvailableException(RETRIEVER_SERVICE_NOT_AVAILABLE_MSG, ResponseCode.COBA_READ_DATA_TEMPORARY_ERROR);
}
return tableFetcher;
}
I want to write the test for the catch block. So tried to write the test case in below.
#Test
public void testapplyConfigUpdate() throws GlobalTableException
{
exception.expect(ServiceNotAvailableException.class);
globalTableRetriever.set(null);
tableFetcher = globalTableRetriever.get();
assertThat(tableFetcher).isNull();
myTableHandler.activate(myOsgiComponentContext);
verify(myCounterRegistratorService, times(1)).incrementCounter(any(CounterInstance.class));
}
But once its entering to getGlobalTableRetrieverer method, the assertion null value is changing to original.
Why do you even need to assert that?
exception.expect(ServiceNotAvailableException.class);
already implies that tableFetcher is null.
Just try this :
#Test
public void testapplyConfigUpdate() throws GlobalTableException
{
exception.expect(ServiceNotAvailableException.class);
globalTableRetriever.set(null);
tableFetcher = globalTableRetriever.get();
}

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.

What's your most reused class?

Every programmer ends up with a set of utility classes after a while. Some of them are true programming pearls and they are reused in several of your projects. For example, in java:
class Separator {
private String separator;
private boolean called;
public Separator(String aSeparator) {
separator = aSeparator;
called = false;
}
#Override
public String toString() {
if (!called) {
called = true;
return "";
} else {
return separator;
}
}
}
and:
public class JoinHelper {
public static <T> String join(T... elements) {
return joinArray(" ", elements);
}
public static <T> String join(String separator, T... elements) {
return joinArray(separator, elements);
}
private static <T> String joinArray(String sep, T[] elements) {
StringBuilder stringBuilder = new StringBuilder();
Separator separator = new Separator(sep);
for (T element : elements) {
stringBuilder.append(separator).append(element);
}
return stringBuilder.toString();
}
}
What is your most reused class?
System.Object - almost all my types extend it.
A utility class that has logging and email functionality. An extensions class that contains extension methods. A reporting class that basically harness the reporting services web service and makes it easy to stream reports as excel, pdf, etc.
Examples...
1.) Utility Class (static)
public static void LogError(Exception ex)
{
EventLog log = new EventLog();
if (ex != null)
{
log.Source = ConfigurationManager.AppSettings["EventLog"].ToString();
StringBuilder sErrorMessage = new StringBuilder();
if (HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
{
sErrorMessage.Append(HttpContext.Current.Request.Url.ToString() + System.Environment.NewLine);
}
sErrorMessage.Append(ex.ToString());
log.WriteEntry(sErrorMessage.ToString(), EventLogEntryType.Error);
}
}
2.) Extensions Class
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static short getLastDayOfMonth(short givenMonth, short givenYear)
{
short lastDay = 31;
switch (givenMonth)
{
case 4:
case 6:
case 9:
case 11:
lastDay = 30;
break;
case 2:
if ((int)givenYear % 4 == 0)
{
lastDay = 29;
}
else
{
lastDay = 28;
}
break;
}
return lastDay;
}
Most reused but boring:
public static void handleException(Exception e) throws RuntimeException {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e); //NOPMD
}
Less boring (also methods for building lists and sets):
/**
* Builds a Map that is based on the Bean List.
*
* #param items Bean List items
* #param keyField Bean Field that will be key of Map elements (not null)
* #return a Map that is based on the Bean List
*/
#SuppressWarnings("unchecked")
public static <T, K> Map<K, T> buildMapFromCollection(final Collection<T> items,
boolean linkedMap,
final String keyField,
final Class<K> keyType) {
if (items == null) {
return Collections.emptyMap();
}
if (keyField == null) {
throw new IllegalArgumentException("KeyField is null");
}
final Map<K, T> result;
if (linkedMap) {
result = new LinkedHashMap<K, T>();
} else {
result = new HashMap<K, T>();
}
BeanMapper mapper = null;
for (final T item : items) {
if (mapper == null) {
mapper = new BeanMapper(item.getClass());
}
final K key = (K) mapper.getFieldValue(item, keyField);
result.put(key, item);
}
return result;
}
Logger class: Which logs the flow of control in a log file.
Configuration Reader/Setter: which reads the configuration from ini/xml file and sets the environment of the application
Most reused? Hmmm...
boost::shared_ptr<> with boost::weak_ptr<>
probably most reused (also probably most bang-for-buck ratio)
Globals
Just a simple class with static DBConnString, and a few other app wide settings.
Have reused the simple file in about 2 dozen projects since working with .Net
A ConcurrentDictionary I wrote, which I now seem to use everywhere (I write lots of parallel programs)