How to test 2 log messages in JUnit and Mockito - java

I am very new to JUnit and Mockito. I am trying to write a test case using JUnit and Mockito to verify log messages. I have 2 log messages in my code.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public int run(final String[] args) throws Exception {
if (args.length != 2) {
log.info("Usage: input-path output-path");
log.info("Input and output path are required in the same sequence");
System.exit(1);
}
final String inputPath = args[0];
final String outputPath = args[1];
//some code
return 0;
}
The test case that I have written is
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
#RunWith(MockitoJUnitRunner.class)
public class testRun {
#Mock
private Appender mockAppender;
#Before
public void setup() {LogManager.getRootLogger().addAppender(mockAppender);}
#After
public void teardown() {LogManager.getRootLogger().removeAppender(mockAppender);}
#Test
public void testValidArguments() {
//some code
Logger.getLogger(TryTest.class).info("Usage: input-path output-path");
Logger.getLogger(TryTest.class).info("Input and output path are required in the same sequence");
ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appender,times(2)).doAppend(argument.capture());
assertEquals(Level.INFO, argument.getValue().getLevel());
assertEquals("Usage: input-path output-path", argument.getValue().getMessage());
assertEquals("Input and output path are required in the same sequence", argument.getValue().getMessage());
}
}
I have seen some solutions but they require to create another class which I do not want. Also while I execute the code it is taking the second value i.e., "Input and output path are required in the same sequence". The code executes fine if there is only one log message. I can put both the messages in one log.info if it cannot be solved. However, I do wish to know if there are any possible solution to this particular problem.

If you are using sl4j logger you could use ListAppender:
#Test
void test() {
Logger logger = (Logger) LogFactory.getLogger(YourClass.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
YourClass yourClass = new YourClass();
yourClass.callYourMethodWithLogs();
List<ILoggingEvent> logsList = listAppender.list;
//make assertions with logList
}

Related

Why we need to mock static class before every test case in same class

I have a test class with two test cases . I am using Junit 4. My these test cases are using static class. So I mocked a static class in #BeforeClass method so that it is only mocked once before the start of execution of test cases. but in this case only first test case works fine and rest of all test cases fails. so for that I mocked my static class in #Before method so that it is been mocked before every test case execution. So I want to understand that why is there need to mock the static class before every test case and why cant we mock it only once before start of execution of class.
import com.walmart.fulfillment.encryption.logging.HttpThreadBusinessContext;
import com.walmart.rxorderdetailsfulfillment.data.LabelOverFlowOrderRepo;
import com.walmart.rxorderdetailsfulfillment.models.entity.LabelOverFlowOrder;
import com.walmart.rxorderdetailsfulfillment.models.entity.LabelOverFlowPK;
import com.walmart.rxorderdetailsfulfillment.models.request.LabelOverFlowRequest;
import com.walmart.rxorderdetailsfulfillment.models.response.LabelOverFlowResponse;
import com.walmart.rxorderdetailsfulfillment.util.LabelOverFlowUtility;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
#RunWith(PowerMockRunner.class)
#PrepareForTest({LabelOverFlowUtility.class,HttpThreadBusinessContext.class,LabelOverFlowOrderRepo.class,LabelOverFlowResponse.class,LabelOverFlowOrder.class,LabelOverFlowPK.class})
public class LabelOverFlowRequestHandlerTest {
static int count =0;
LabelOverFlowRequest labelOverFlowRequest;
#InjectMocks
LabelOverFlowRequestHandler labelOverFlowRequestHandler;
#Mock
HttpThreadBusinessContext httpThreadBusinessContext;
#Mock
LabelOverFlowOrderRepo labelOverFlowOrderRepo;
#Mock
LabelOverFlowResponse labelOverFlowResponse;
#Mock
LabelOverFlowOrder labelOverFlowOrder;
#Mock
LabelOverFlowPK labelOverFlowPK;
#BeforeClass
public static void initialization(){
//PowerMockito.mockStatic(LabelOverFlowUtility.class);
}
#Before
public void initialization_Before_Every_Test(){
PowerMockito.mockStatic(LabelOverFlowUtility.class);
labelOverFlowRequest = LabelOverFlowRequest.builder().textOverFlow(true).warningOverFlow(true).rxFillId(555).siteNbr(5550).countryCode("US").build();
}
/**
* This test case is use to check success is returned after saving data to DB.
*/
#Test
public void processSaveLabelOverFlowResquestWithSuccess() {
when(LabelOverFlowUtility.getLabelOverFlowPK(Mockito.any())).thenReturn(labelOverFlowPK);
when(LabelOverFlowUtility.getLabelOverFlowOrder(Mockito.any())).thenReturn(labelOverFlowOrder);
when(labelOverFlowOrderRepo.save(Mockito.any())).thenReturn(labelOverFlowResponse);
when(LabelOverFlowUtility.getLabelOverFlowResponse(Mockito.any())).thenCallRealMethod();
Mockito.doReturn(labelOverFlowOrder).when(labelOverFlowOrderRepo).save(Mockito.any());
assertTrue(labelOverFlowRequestHandler.processSaveLabelOverFlowResquest(labelOverFlowRequest).getResponseText().equals("success"));
}
/**
* This test case is ued to check if data is not saved to DB
*/
#Test
public void processSaveLabelOverFlowResquestWithFailure() {
when(LabelOverFlowUtility.getLabelOverFlowPK(Mockito.any())).thenReturn(labelOverFlowPK);
when(LabelOverFlowUtility.getLabelOverFlowOrder(Mockito.any())).thenReturn(labelOverFlowOrder);
when(labelOverFlowOrderRepo.save(Mockito.any())).thenReturn(labelOverFlowResponse);
when(LabelOverFlowUtility.getLabelOverFlowResponse(Mockito.any())).thenCallRealMethod();
Mockito.doThrow(new RuntimeException()).when(labelOverFlowOrderRepo).save(Mockito.any());
assertTrue(labelOverFlowRequestHandler.processSaveLabelOverFlowResquest(labelOverFlowRequest).getResponseText().equals("failure"));
}
}
LabelOverFlowUtility.class is a static class, there should be no need to mock it at all if the methods are deterministic(given same input same thing happens).
I may be misunderstanding how this class operates.

JUnit Mock Singleton Class with Environment Variables

I have a singleton Class as follows:
public class PropertiesSingleton {
private static PropertiesSingleton instance;
private static ApplicationContext ctx = new
AnnotationConfigApplicationContext(PropertiesConfig.class);
public static PropertiesSingleton getInstance(){
if(instance == null){
synchronized (PropertiesSingleton.class) {
if(instance == null){
instance = new PropertiesSingleton();
}
}
}
return instance;
}
public Environment env(){
return ctx.getEnvironment();
}
}
The PropertiesConfig Class as follows:
#Configuration
#ComponentScan("someComponent")
#PropertySources({#PropertySource("file:${someName}/foo/foo.properties"),
#PropertySource("classPath:Properties")
})
public class PropertiesConfig {
#Autowired
private Environment env;
}
And it is being called in Controller as Follows:
#CrossOrigin
#RestController
#RequestMapping(value="/mappingUrl")
public class MappingController{
static Environment env = PropertiesSingleton.getInstance().env();
}
What I am trying to do is get the mocked value for env in controller and I am trying it following way:
#Before
public void setUp() throws Exception {
MockEnvironment env = new MockEnvironment();
env.setProperty("serverName", "test");
PropertiesSingleton environmentMock =
PowerMockito.mock(PropertiesSingleton.class);
Whitebox.setInternalState( PropertiesSingleton.class, "INSTANCE",
environmentMock );
when(environmentMock.getInstance().env())
.thenReturn(env);
}
But I get following errors:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
and looking at stack trace I see following:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [propertiesConfig.class]
org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.
Any help is appreciated......
EDIT:
Here is my full test method--
import javax.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.junit.Before;
import org.apache.log4j.Logger;
import static org.mockito.Mockito.*;
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.charset.Charset;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
#RunWith(PowerMockRunner.class)
#PrepareForTest(PropertiesSingleton.class)
#TestPropertySource(locations="classpath:someclassPath")
public class MappingControllerTest{
private MockMvc mockMvc;
JSONObject obj = new JSONObject("{"
+ "\"_id\": \"184DZ01C\","
+ "\"text\": \"textTest\","
+ "\"image\" : \"Test.png\","
+ "\"link\" : \"www.testFile.com\","
+ "\"title\" : \"testTitle\","
+ "\"weight\" : \"0\","
+ "}");
public static final MediaType APPLICATION_JSON_UTF8 = new
MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
#InjectMocks
#Spy
MappingController _mappingController = new MappingController();
#Mock
private Appender logAppender;
#Mock
private Environment environmentMock;
#Mock
private PropertiesSingleton singletonMock;
#Before
public void setUp() throws Exception {
Logger logger = Logger.getLogger(ReviewWfEndpoint.class);
logger.addAppender(logAppender);
logger.setLevel(Level.INFO);
}
#Test
public void TestReviewWfEndpoint_pass()
throws Exception {
String expectedServer = "test";
String expectedServerPropertyName = "serverName";
PowerMockito.mockStatic(PropertiesSingleton.class);
when(PropertiesSingleton.getInstance()).thenReturn(singletonMock);
when(singletonMock.env()).thenReturn(environmentMock);
when(environmentMock.getProperty(expectedServerPropertyName))
.thenReturn(expectedServer);
this.mockMvc.perform(post("/mappingUrl/map")
.contentType(APPLICATION_JSON_UTF8)
.content(jString)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
and in my controller I use env like this:
#CrossOrigin
#RestController
#RequestMapping(value="/mappingUrl")
public class MappingController{
static Environment env = PropertiesSingleton.getInstance().env();
#RequestMapping(value="/map", method=RequestMethod.POST,
produces="application/json")
public ResponseEntity<Object> map(#RequestBody String jsonString){
String environmentName =
env.getProperty("Constant");
}
}
SLF4J is probably loaded by Spring (possibly somewhere in the call stack starting with AnnotationConfigApplicationContext) but you can ignore that (and will probably disappear after setting up your test correctly).
Anyway, you need to do a few things to completely mock your singleton and return your custom environment instance. Furthermore, with this you no longer need Whitebox to update the singleton state, you just define the mock's behavior:
use the specific PowerMockRunner so that the Powermock "magic" can happen
suppress the static initialization sections inside the singleton
mockStatic your singleton (for getInstance())
define the expected behavior step by step as Powermock does not yet support DEEP STUBBING (aka environmentMock.getInstance().env())
You can find below a complete example. Please note that in my sources:
I've used a mock for the environment as well since you did not share MockEnvironment (it was also easier for me)
for brevity, I changed MappingController to make static Environment env public so I can quickly check my expected value (also you did not share the code that uses it). Please do not do this in production
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.core.env.Environment;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
// use a special runner
#RunWith(PowerMockRunner.class)
// suppress static initialization block in singleton
#SuppressStaticInitializationFor("com.example.PropertiesSingleton")
public class SingletonTest {
// create the mock to return by getInstance()
#Mock
private PropertiesSingleton singletonMock;
// environment mock for quick test
#Mock
private Environment environmentMock;
#Test
public void testSomeMethod() throws Exception {
String expectedServer = "test";
String expectedServerPropertyName = "serverName";
// define behavior
// please note power mockito does not yet support DEEP STUBBING (https://github.com/powermock/powermock/issues/507), so multiple "whens" must be used
mockStatic(PropertiesSingleton.class);
when(PropertiesSingleton.getInstance()).thenReturn(singletonMock);
when(singletonMock.env()).thenReturn(environmentMock);
when(environmentMock.getProperty(expectedServerPropertyName)).thenReturn(expectedServer);
// invoke the object under test and check results
assertThat(MappingController.env.getProperty(expectedServerPropertyName), is(expectedServer));
}
}
P.S. you may want to consider giving this a quick read: the benefits of constructor injection vs field injection (aka #Autowired Environment env; in your sample)

How to verify arguments passed to a static function with Java JUnit and Mockito (Spring Boot)

I'm new to all the mentioned technologies so it might be a stupid question.
We have a spring boot application where we need to write to a PostgreSQL-Database via JDBC.
Therefore we need the static DriverManager.getConnection() method to open the connection.
Now in my unit tests I don't want to call this class directly.
Instead I want to check, that the DriverManager.getConnection() is called with the correct String as that is my expected observable external behavior.
I encapsulated this behavior into a ConnectionFactory with the method newConnection(ConnectionType.POSTGRESQL) because we got more than one Database to use in this Application.
Now I can't find a way to verify via Mockito that this external dependency was called with the correct String like you could with an instance:
DriverManager dm = mock(DriverManager);
connectionFactory.newConnection(ConnectionType.POSTGRESQL);
verify(dm).getConnection("theConnectionStringToBeExpected");
So how to do this with the static dependency?
I tried the Captor-way but this seems to only work for direct usage like
mockStatic(DriverManager.class);
final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// What I have to do to verify
DriverManager.getConnection("theActualConnectionString");
// What I would like to do to verify
// connectionFactory.newConnection(ConnectionType.POSTGRESQL);
verifyStatic();
StaticService.getConnection(captor.capture());
assertEquals("theExpectedConnectionString", captor.getValue());
Edit:
Here is the nasty little workaround which I currently use for another server...
public void driverManagerIsCorrectlyCalledForAds() throws Exception {
mockStatic(DriverManager.class);
doNothing().when(databaseDriverLoader).load();
final Connection expectedConnection = mock(Connection.class);
when(DriverManager.getConnection("jdbc:extendedsystems:advantage://server:1337/database_name;user=user;password=password;chartype=ansi"))
.thenReturn(expectedConnection);
Connection actualConnection = connectionFactory.newConnection(ConnectionType.ADS);
assertEquals(expectedConnection, actualConnection);
}
Edit 2:
TestClass:
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.*;
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(SpringRunner.class)
#PrepareForTest({ConnectionFactory.class, DriverManager.class, DatabaseDriverInformation.class})
public class ConnectionFactoryTest {
#InjectMocks
ConnectionFactory connectionFactory;
#Mock
DatabaseDriverInformation databaseDriverInformation;
#Mock
DatabaseProperties databaseProperties;
#Mock
DatabaseProperties.Pg pg;
#Mock
DatabaseDriverLoader databaseDriverLoader;
#Before
public void setUp() {
doReturn(pg).when(databaseProperties).getPg();
doReturn("server").when(ads).getServer();
doReturn(1338).when(ads).getPort();
doReturn("database_name").when(ads).getDatabasename();
doReturn("user").when(ads).getUser();
doReturn("password").when(ads).getPassword();
}
#Test
public void driverManagerIsCorrectlyCalledForPg() throws Exception {
mockStatic(DriverManager.class);
doNothing().when(databaseDriverLoader).load();
Connection expectedConnection = mock(Connection.class);
when(DriverManager.getConnection("jdbc:postgresql://server:1338/database_name;user=user;password=password"))
.thenReturn(expectedConnection);
Connection actualConnection = connectionFactory.newConnection(ConnectionType.POSTGRESQL);
assertEquals(expectedConnection, actualConnection);
}
}
Class under Test:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.*;
#Service()
public class ConnectionFactory {
#Autowired
private DatabaseDriverLoader databaseDriverLoader;
#Autowired
DatabaseProperties databaseProperties;
public Connection newConnection(ConnectionType connectionType) {
databaseDriverLoader.load();
final String connectionString = connectionStringFor(connectionType);
try {
return DriverManager.getConnection(connectionString);
} catch (SQLException sqlException) {
throw new RuntimeException("Couldn't connect to Server");
}
}
private String connectionStringFor(ConnectionType connectionType) {
switch (connectionType) {
case ADS:
return this.adsConnectionString();
case POSTGRESQL:
return this.pgConnectionString();
default:
throw new RuntimeException("Invalid connection Type requested!");
}
}
private String adsConnectionString() {
return new StringBuilder()
.append("jdbc:extendedsystems:advantage://")
.append(databaseProperties.getAds().getServer())
.append(":")
.append(databaseProperties.getAds().getPort())
.append("/")
.append(databaseProperties.getAds().getDatabasename())
.append(";user=")
.append(databaseProperties.getAds().getUser())
.append(";password=")
.append(databaseProperties.getAds().getPassword())
.append(";chartype=ansi")
.toString();
}
private String pgConnectionString() {
return new StringBuilder()
.append("jdbc:postgresql://")
.append(databaseProperties.getPg().getServer())
.append(":")
.append(databaseProperties.getPg().getPort())
.append("/")
.append(databaseProperties.getPg().getDatabasename())
.append("?user=")
.append(databaseProperties.getPg().getUser())
.append("&password=")
.append(databaseProperties.getPg().getPassword())
.toString();
}
}
I removed the package-names, some specific imports and some unnecessary tests which are working.
After some search I found this: How to verify static void method has been called with power mockito
In Essence:
first:
mockStatic(ClassWithStaticFunctionToVerify.class)
second:
Execute the Code that will call the function you want to verify later
third:
verifyStatic();
ClassWithStaticFunctionToVerify.functionYouWantToVerify("ParameterValueYouExpect");
With it's help I got the following Solution which works fine:
#Test
public void driverManagerIsCorrectlyCalledForPg() throws Exception {
// Arrange
mockStatic(DatabaseProperties.Pg.class);
doReturn(pg).when(databaseProperties).getPg();
doReturn("server").when(pg).getServer();
doReturn(1338).when(pg).getPort();
doReturn("database_name").when(pg).getDatabasename();
doReturn("user").when(pg).getUser();
doReturn("password").when(pg).getPassword();
mockStatic(DriverManager.class);
doNothing().when(databaseDriverLoader).loadAdsDriverClass();
doNothing().when(databaseDriverLoader).loadPgDriverClass();
when(DriverManager.getConnection(anyString())).thenReturn(expectedConnection);
// Act
connectionFactory.newConnection(ConnectionType.POSTGRESQL);
// Assert
verifyStatic();
DriverManager.getConnection("jdbc:postgresql://server:1338/database_name?user=user&password=password");
}

Mocking getResource in static block with PowerMock

How to mock getResourceAsStream in the static block?
I think it is untestable.
I reviewed SO and cannot find the answer. The closes-SO-post-here does not address the issue as the call to getResourceAsAStream in the post is not from a static block.
I tried PowerMock, and run into number of limitations. First if I want to mock SomeProperties.class.getResourceAsStream - the static block will execute, as I will need to refer to the class itself. I can suppress static block to prevent doing so, but this will prevent me from getting the static block to execute at all. The solution would be to postpone the execution of the static block until after someProperties.class.getResourceAsStream is mocked.
I do not think it is possible though.
It seems that this code is purely untestable;
Any other ideas?
Here is the code [and a link to GITHUB]:
package com.sopowermock1;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SomeProperties {
private static Properties props = new Properties();
static {
InputStream is = SomeProperties.class.getResourceAsStream("/some.properties");
try {
props.load(is);
System.out.println("Properties.props.keySet() = " + props.keySet());
} catch (IOException e) {
// How test this branch???
System.out.println("Yes. We got here.");
throw new RuntimeException(e);
}
}
private SomeProperties() {}; // to makes life even harder...
public static String getVersion() {
return props.getProperty("version");
}
}
And here is the test GITHUB Link
package com.sopowermock1;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.sopowermock1.SomeProperties;
#RunWith(PowerMockRunner.class)
#PrepareForTest(SomeProperties.class)
// This will prevent running static block completely:
// #SuppressStaticInitializationFor("com.sopowermock1.SomeProperties")
public class SomePropertiesTest {
#Mock
private static InputStream streamMock;
#Before
public void setUp() {
MockitoAnnotations.initMocks(SomeProperties.class);
System.out.println("test setUp");
}
#Test(expected = RuntimeException.class)
public void testStaticBlock() {
PowerMockito.mockStatic(SomeProperties.class); // this will mock all static methods (unwanted as we want to call getVersion)
// This will cause static block to be called.
PowerMockito.when(SomeProperties.class.getResourceAsStream("/some.properties")).thenReturn(streamMock);
SomeProperties.getVersion();
}
}
Any ideas?. Full GITHUB source is here.
as mention in How to mock getResourceAsStream method using PowerMockito and JUnit?, use Extract Delegate , then mock the delegate class such as XXStreamFetcher, and then you can test it.

Junit: How to know line number in parameter file

I have a method in junit that is responsible for checking errors in a very large file (more than 200k lines).
I would like to know if there is any variable in which Junit put the lines that have the file and the line in which he is doing the test, in order to use them.
I know that in testCase() there is a private variable that contains the line on which the test is running, but I can not access it, any advice?
The code used is like this:
#Test
#FileParameters("fileparameter")
public void testFechaAlteracionExpedienteFS(String line) {
String TEST= 'test';
assertThat(TEST).overridingErrorMessage("Expected: <%s> - but it was: <%s>", line, TEST, ConstantesSql.getConsulta()).isEqualTo(line);
I'm using Maven with Junit 4+.
Why not use simple java api?
Documentation: http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-
Use a parameterized test:
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
#RunWith(Parameterized.class)
public class ParameterizedTest {
#Parameter(0)
public File file;
#Parameter(1)
public String line;
#Parameters(name = "{index}: {0}")
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] { { new File("/path/to/file1"), "line1" },
{ new File("/path/to/file2"), "line2" },
{ new File("/path/to/file3"), "line3" } });
}
#Test
public void test() {
// Your test code here (read file and line variables)
}
}

Categories