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

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.

Related

How to write unit test for spring cloud stream function based method?

When I try to test a spring cloud stream function based method, it always happens NullPointerException about InputDestination.
I have two questions:
It's hard for me to know how to write UT from the official doc. official test doc
Besides, how to write integration Test if test file has some dependencies. It seems create a new context and always has NoSuchBeanDefination error.
I have tried as flow, but the context can not find some dependency beans.
#Test
public void sampleTest() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestChannelBinderConfiguration.getCompleteConfiguration(
MyTestConfiguration.class))
.run("--spring.cloud.function.definition=uppercase")) {
InputDestination source = context.getBean(InputDestination.class);
OutputDestination target = context.getBean(OutputDestination.class);
source.send(new GenericMessage<byte[]>("hello".getBytes()));
assertThat(target.receive().getPayload()).isEqualTo("HELLO".getBytes());
}
}
So I just want to write UT, but still have NPE.
Here is my code.
#Bean
public Function<Message<List<DemoBean>>, Message<DemoBean>> findFirstBean( ){
return message -> {
List<DemoBean> demoBeans = message.getPayload();
return MessageBuilder.withPayload(demoBeans.get( 0 )).build();
};
}
Here is my test.
#SpringBootTest
#ActiveProfiles(profiles = "local")
#Import({ TestChannelBinderConfiguration.class})
class FunctionDemoTest {
#Autowired
private InputDestination inputDestination;
#Autowired
private OutputDestination outputDestination;
private FunctionDemo functionDemo;
// some dependency need to mock
private DemoService demoService;
#BeforeEach
void setUp() {
demoService = Mockito.mock( DemoService.class );
functionDemo = new FunctionDemo( demoService);
}
#Test
public void findFirstBeanTest() {
DemoBean demoBean = new DemoBean();
demoBean.setName("Howard");
demoBean.setAge( 1 );
DemoBean demoBean1 = new DemoBean();
demoBean1.setName("Frank");
demoBean1.setAge( 2 );
List<DemoBean> demoBeanList = new ArrayList<>();
demoBeanList.add( demoBean );
demoBeanList.add( demoBean1 );
Message<List<DemoBean>> inputMessage = MessageBuilder.withPayload(demoBeanList).build();
inputDestination.send(inputMessage,"findFirstBean-in-0");
Assertions.assertNotNull( outputDestination.receive( 10000, "findFirstBean-out-0") );
}
}
Here is error:
java.lang.NullPointerException: while trying to invoke the method org.springframework.messaging.SubscribableChannel.send(org.springframework.messaging.Message) of a null object returned from org.springframework.cloud.stream.binder.test.InputDestination.getChannelByName(java.lang.String)
at org.springframework.cloud.stream.binder.test.InputDestination.send(InputDestination.java:89)
at com.successfactors.caf.listener.FunctionDemoTest.raePdrResultProcessor(FunctionDemoTest.java:82)
Well, I know the root cause of NPE.
Message<byte[]> receive(long timeout, String bindingName)
It seems should be destinationName instead of bindingName in source code.
Any other answers would be appreciated.

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.

Test execution in Spring Boot fails due to failed config load

I am trying to test my application and running into troubles:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = MainConfiguration.class)
public class ProductionDataRestClientTest {
#Test
public void testGetProductionDataAsync() {
}
}
The MainConfiguration class is as follows:
#Data
#Configuration
#Slf4j
#PropertySource(value = {
"classpath:/conf/application.properties", "classpath:/conf/application.build.properties",
"file:${configPath}/application.properties" }, ignoreResourceNotFound = true)
public class MainConfiguration {
#Value("${app.configName}")
private String configName;
#Value("${project.name}")
private String appName;
#Value("${project.version}")
private String appVersion;
#Value("${app.historySize}")
private int historySize;
#Value("${app.processOnlyVisibleEnvironments}")
private Boolean processOnlyVisibleEnvironments;
#PostConstruct
private void logConfig() {
appName = WordUtils.capitalize(appName);
log.info("constructed config: " + configName);
log.info(this.toString());
}
}
And the application.properties file is here:
app.configName=Internal Classpath
app.historySize=25
app.processOnlyVisibleEnvironments=true
client.timeout.connect=30000
client.timeout.read=30000
threading.pool.size.environmentProcessing=5
threading.pool.size.webServiceRequesting=10
My problem is, that Spring seems not to resolve the value identifiers as in normal executions, so the following stacktrace is thrown:
Caused by: java.lang.NumberFormatException: For input string: "${app.historySize}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.valueOf(Integer.java:766)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:194)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:464)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:437)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:195)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:125)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
... 47 more
I don't have any clue, I tried many different things, nothing worked.
Thanks in advance :)
There was a very simple way to solve this issue:
// To resolve ${} in #Value
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
This has to be a method of the loaded Configuration-file and helps resolving the placeholders.
Thanks for helping ;)

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());
}

How do I invoke Multiple Startup Projects when running a unit tests in Debug Mode

This seems like a simple thing to do but I can't seem to find any info anywhere! I've got a solution that has a service that we run in 'Console Mode' when debugging. I want it to be started and 'attached' when I run my unit test from Visual Studio.
I'm using Resharper as the unit test runner.
Not a direct answer to your question, BUT
We faced a similar problem recently and eventually settled on a solution using AppDomain
As your solution is already running as a Console project it would be little work to make it boot in a new AppDomain. Furthermore, you could run Assertions on this project as well as part of unit testing. (if required)
Consider the following static class Sandbox which you can use to boot multiple app domains.
The Execute method requires a Type which is-a SandboxAction. (class definition also included below)
You would first extend this class and provide any bootup actions for running your console project.
public class ConsoleRunnerProjectSandbox : SandboxAction
{
protected override void OnRun()
{
Bootstrapper.Start(); //this code will be run on the newly create app domain
}
}
Now to get your app domain running you simply call
Sandbox.Execute<ConsoleRunnerProjectSandbox>("AppDomainName", configFile)
Note you can pass this call a config file so you can bootup your project in the same fashion as if you were running it via the console
Any more questions please ask.
public static class Sandbox
{
private static readonly List<Tuple<AppDomain, SandboxAction>> _sandboxes = new List<Tuple<AppDomain, SandboxAction>>();
public static T Execute<T>(string friendlyName, string configFile, params object[] args)
where T : SandboxAction
{
Trace.WriteLine(string.Format("Sandboxing {0}: {1}", typeof (T).Name, configFile));
AppDomain sandbox = CreateDomain(friendlyName, configFile);
var objectHandle = sandbox.CreateInstance(typeof(T).Assembly.FullName, typeof(T).FullName, true, BindingFlags.Default, null, args, null, null, null);
T sandBoxAction = objectHandle.Unwrap() as T;
sandBoxAction.Run();
Tuple<AppDomain, SandboxAction> box = new Tuple<AppDomain, SandboxAction>(sandbox, sandBoxAction);
_sandboxes.Add(box);
return sandBoxAction;
}
private static AppDomain CreateDomain(string name, string customConfigFile)
{
FileInfo info = customConfigFile != null ? new FileInfo(customConfigFile) : null;
if (!string.IsNullOrEmpty(customConfigFile) && !info.Exists)
throw new ArgumentException("customConfigFile not found using " + customConfigFile + " at " + info.FullName);
var appsetup = new AppDomainSetup();
//appsetup.ApplicationBase = Path.GetDirectoryName(typeof(Sandbox).Assembly.Location);
appsetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
if (customConfigFile==null)
customConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
appsetup.ConfigurationFile = customConfigFile;
var sandbox = AppDomain.CreateDomain(
name,
AppDomain.CurrentDomain.Evidence,
appsetup);
return sandbox;
}
public static void DestroyAppDomainForSandbox(SandboxAction action)
{
foreach(var tuple in _sandboxes)
{
if(tuple.Second == action)
{
AppDomain.Unload(tuple.First);
Console.WriteLine("Unloaded sandbox ");
_sandboxes.Remove(tuple);
return;
}
}
}
}
[Serializable]
public abstract class SandboxAction : MarshalByRefObject
{
public override object InitializeLifetimeService()
{
return null;
}
public void Run()
{
string name = AppDomain.CurrentDomain.FriendlyName;
Log.Info("Executing {0} in AppDomain:{1} thread:{2}", name, AppDomain.CurrentDomain.Id, Thread.CurrentThread.ManagedThreadId);
try
{
OnRun();
}
catch (Exception ex)
{
Log.Error(ex, "Exception in app domain {0}", name);
throw;
}
}
protected abstract void OnRun();
public virtual void Stop()
{
}
}