Mockito test for MultipartFile.transferto() in Service layer - java

public void saveFile(MultipartFile file , int id) throws IOException {
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("-yyMMddHHmmss"));
String destination = goldenFileLocation + "/" + file.getOriginalFilename() + date;
file.transferTo(new File(destination));
}
I need to write a Mockito test for the above service layer code. I have the below code but not sure how to test if the file exists in the mentioned location.
#Test
public void testSaveFile() throws IOException {
MockMultipartFile firstFile = new MockMultipartFile("pdf", "response.pdf", "multipart/form-data", "data".getBytes());
saveFile(firstFile,1);
//check if file got stored in the mentioned location
}

Related

SpringBoot absolute path clarification

I'm new to SpringBoot web dev.
I need to save an image to a directory in the current project. I have given path as "String uploaddir = "./src/main/imageuploads/"+ savedadvert.getId();" but the image not save to the "./src/main/imageuploads/" directory in eclipse project.
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(#RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {
model.addAttribute("advertsim",new advertsummary());
advertsummary advert = new advertsummary();
String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
advert.setFile1Url(file1Urlname);
advertsummary savedadvert = AdvertService.addadvert(advert);
String uploaddir = "./src/main/imageuploads/"+ savedadvert.getId();
FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);
return "uploadview";
}
This is the saveFile method for ref.
public static void saveFile(MultipartFile multipartFile, String fileName, String uploadDir) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
System.out.println(filePath.toFile().getAbsolutePath());
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
}
I need to upload the image to this directory,
when I get the absolute path, it shows like this "/Users/chathura/eclipse/jee-2021-03/Eclipse.app/Contents/MacOS/./src/main/imageuploads/24/new file.jpg".
There is no way to go to this directory but I can access that directory using the terminal.
Please tell me what is the mistake here?
Note : I'm using macos
Thanks in advance
Could you try 'src/main/resources/imagesuploads' (without .)
Just a reminder: This directory will disappear when you package your application (production mode)
This directory should be configurable from an external file (application. properties for example)
Thank you Ali, your response gave a lead to the solution. My project sits on MacOS partition therefore, I couldn't write a file without permission. I simply changed the location to another partition and it worked.
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(#RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {
model.addAttribute("advertsim",new advertsummary());
advertsummary advert = new advertsummary();
String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
advert.setFile1Url(file1Urlname);
advertsummary savedadvert = AdvertService.addadvert(advert);
String uploaddir = "/Volumes/My Data/Fileupload"+ savedadvert.getId();
FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);
return "uploadview";
}
Thank you

Mocking files and unit tests with temporaryFolder

I have a method which is searching and adding all java files in directory to List:
public List<File> findJavaFiles(File root, String path) {
String suffix = ".java";
List<File> list = new ArrayList<>();
if (root.isDirectory()) {
File[] files = root.listFiles();
if (files != null) {
for (File file : files) {
list.addAll(findJavaFiles(file, suffix));
}
}
} else if (root.getName().endsWith(suffix)) {
list.add(root);
}
return list;
}
It works, but the problem is that I want to create unit test (I'm starting "fun" with mocks tests). I know I should use temporaryFolder and mock java files, so I have something like this:
#Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
#Before
public void setUp() throws IOException {
file1 = mock(File.class);
when(file1.getName()).thenReturn("file1.java");
when(file1.length()).thenReturn(1L);
file2 = mock(File.class);
when(file2.getName()).thenReturn("file2.java");
when(file2.length()).thenReturn(5L);
file3 = mock(File.class);
when(file3.getName()).thenReturn("file3.java");
when(file3.length()).thenReturn(3L);
file4 = mock(File.class);
when(file4.getName()).thenReturn("file4.jpg");
when(file4.length()).thenReturn(10L);
temporaryFolder.newFile(file1.getName());
temporaryFolder.newFile(file2.getName());
temporaryFolder.newFile(file3.getName());
temporaryFolder.newFile(file4.getName());
And unit test:
#Test
public void findJavaFilesIsCorrect() {
//given
List<File> expectedResult = List.of(file1, file2, file3);
//when
when(fileService.findJavaFiles(ArgumentMatchers.anyString())).thenCallRealMethod();
List<File> result = fileService.findJavaFiles(System.getProperty(System.getProperty("java.io.tmpdir")));
//then
Assert.assertEquals(expectedResult, result);
}
And test failed... Result List is empty... But I dont know why
You need to set the java.io.tmpdir value.

How to test IO exceptions?

There is a WriterReader object in my code which uses FileOutputStream and ObjectOutputStream. Therefore writing an object to a file throws IO exceptions. I am trying a way to handle FileNotFound exception and throw other IO exceptions. Also while handling FileNotFound exception, I want to test it with JUnit 5.
I tried the following test, using date as a unique file name, asserting that file DNE, then writing the object to a file that DNE, which SHOULD trigger FileNotFound exception. And while handling that exception, I basically create a new file with the same name, also creating dirs before that.
Code:
#Test
void testWriteReadObjectFileNotFound() {
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
File file = new File("data\\test\\" + timeStamp );
try {
assertFalse(file.exists());
System.out.println(file.exists());
String s1 = "testObj";
wr.writeObject(s1, file.getName());
String s2 = (String) wr.readObject(file.getName());
assertEquals("testObj", s2);
assertTrue(file.exists());
} catch (IOException e) {
fail();
} catch (ClassNotFoundException e) {
fail();
}
file.delete();
}
//MODIFIES: file at filepath
//EFFECTS: Writes given object to file
public void writeObject(Object serObj, String fileName) throws IOException {
FileOutputStream fileOut;
ObjectOutputStream objectOut;
try {
new FileOutputStream(filepath + fileName);
} catch (FileNotFoundException e) {
File file = new File(filepath + fileName);
file.getParentFile().mkdirs();
file.createNewFile();
} finally {
fileOut = new FileOutputStream(filepath + fileName);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serObj);
objectOut.close();
}
}
But in my code coverage it shows that the lines :
catch (FileNotFoundException e) {
File file = new File(filepath + fileName);
file.getParentFile().mkdirs();
file.createNewFile();
is not covered. Can one explain me this situation?
Edit:
After I updated my code with suggestions, now intelliJ shows that my tests cover write method, while an online Jacoco Code Coverage service shows that its not covered at all.
Sessions:
jdk.nashorn.api.scripting.NashornScriptEngineFactory 85de62d029761869
model.Coach 204e934c34a92289
model.CounterStrikePlayer 48cfc6cf38fe6003
model.Game b60d406f9ed032d3
model.LeagueOfLegendsCoach 6a57ce5ef266c6fd
model.LeagueOfLegendsPlayer 9adbbaea6a1e6188
model.Player 6ce725a3657ac0c8
model.Team 13c05b5862e5b9a0
model.WriterReader 6a7b2968db1f8baa
modelTest.CoachTest 7271c28c53da6808
modelTest.CounterStrikePlayerTest ee8e4647ff19f0c0
modelTest.GameTest e5b8c02da0f18042
modelTest.LeagueOfLegendsCoachTest 9092faa361ca76c6
modelTest.LeagueOfLegendsPlayerTest f31d56fa7811133d
modelTest.PlayerTest 1dfe7a02c80688d8
modelTest.WriterReaderTest a0c6c0b3c5015303
org.apiguardian.api.API.Status 0341e8d99fc36573
org.junit.jupiter.api.AssertEquals ae120be259dc6039
org.junit.jupiter.api.AssertFalse 3ec30e2666af3771
org.junit.jupiter.api.AssertTrue bf124afce44d2c84
org.junit.jupiter.api.AssertionUtils 4c69336af9422f48
org.junit.jupiter.api.Assertions bef006507cf5ea35
org.junit.jupiter.api.DisplayNameGenerator 2fa57366e26f369e
org.junit.jupiter.api.DisplayNameGenerator.ReplaceUnderscores a784705e370ef10a
org.junit.jupiter.api.DisplayNameGenerator.Standard 084b890848e1dd9c
org.junit.jupiter.api.TestInstance.Lifecycle 548dd47a98f9c8af
org.junit.jupiter.api.extension.ConditionEvaluationResult 2f9dc9ea54b57975
org.junit.jupiter.api.extension.ExtensionContext 1789eac1274261fc
org.junit.jupiter.api.extension.ExtensionContext.Namespace cd5bcaed161aa28d
org.junit.jupiter.engine.JupiterTestEngine 86aefb99bb14b311
org.junit.jupiter.engine.config.CachingJupiterConfiguration bf4da7e3e8743286
org.junit.jupiter.engine.config.ClassNamePatternParameterConverter db88e74320096433
org.junit.jupiter.engine.config.DefaultJupiterConfiguration 997c6d213eddc2c2
org.junit.jupiter.engine.config.EnumConfigurationParameterConverter 339f5752af685066
org.junit.jupiter.engine.descriptor.AbstractExtensionContext 9bf01323cf853683
org.junit.jupiter.engine.descriptor.ClassExtensionContext 41391528f2b447a4
org.junit.jupiter.engine.descriptor.ClassTestDescriptor 1c76f456279716b9
org.junit.jupiter.engine.descriptor.DisplayNameUtils d2e15432c9a5ae11
org.junit.jupiter.engine.descriptor.ExtensionUtils 115ab989016caec3
org.junit.jupiter.engine.descriptor.ExtensionUtils.IsNonStaticExtensionField 1786ef465b5be8dc
org.junit.jupiter.engine.descriptor.ExtensionUtils.IsStaticExtensionField 31f9cde36a56bb92
org.junit.jupiter.engine.descriptor.JupiterEngineDescriptor 55f20ec61f78c1dc
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext 37e3ac8bbe8deb47
org.junit.jupiter.engine.descriptor.JupiterTestDescriptor 4def5ef6cb345908
org.junit.jupiter.engine.descriptor.LifecycleMethodUtils 1162b59df6db6b33
org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor c5a570f30b7fc2d2
org.junit.jupiter.engine.descriptor.MethodExtensionContext afe114c2ffc920b7
org.junit.jupiter.engine.descriptor.TestInstanceLifecycleUtils 8d8758db35676c1c
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor 8d3942c1a74c018c
org.junit.jupiter.engine.discovery.AbstractMethodResolver 2dfaf6ce646f2bdc
org.junit.jupiter.engine.discovery.DiscoveryFilterApplier e52beeff7f999c17
org.junit.jupiter.engine.discovery.DiscoverySelectorResolver ec3c5a90f0a97450
org.junit.jupiter.engine.discovery.JavaElementsResolver adc00610d0191f30
org.junit.jupiter.engine.discovery.MethodFinder 5ea468d2eb528361
org.junit.jupiter.engine.discovery.NestedTestsResolver 05fbe9d811da3eed
org.junit.jupiter.engine.discovery.TestContainerResolver dfe41adaef62c3e4
org.junit.jupiter.engine.discovery.TestFactoryMethodResolver 0ad6df9dfc31ff24
org.junit.jupiter.engine.discovery.TestMethodResolver c8d14bc2744286af
org.junit.jupiter.engine.discovery.TestTemplateMethodResolver de3e832270e2401e
org.junit.jupiter.engine.discovery.predicates.IsInnerClass f7d9846d00228720
org.junit.jupiter.engine.discovery.predicates.IsNestedTestClass e47ff7cd33073803
org.junit.jupiter.engine.discovery.predicates.IsPotentialTestContainer fcb5565ad4483f6c
org.junit.jupiter.engine.discovery.predicates.IsTestClassWithTests 94179bc44f8c4ff7
org.junit.jupiter.engine.discovery.predicates.IsTestFactoryMethod a2c68978bd6bfbc6
org.junit.jupiter.engine.discovery.predicates.IsTestMethod 8b244977e441886e
org.junit.jupiter.engine.discovery.predicates.IsTestTemplateMethod 0baf1066bf0cbad7
org.junit.jupiter.engine.discovery.predicates.IsTestableMethod 59a0b58a40803fe2
org.junit.jupiter.engine.execution.ConditionEvaluator ed446ee9ecce3d2f
org.junit.jupiter.engine.execution.DefaultTestInstances 37fd85d961d60c98
org.junit.jupiter.engine.execution.ExecutableInvoker cfec2160144fba71
org.junit.jupiter.engine.execution.ExtensionValuesStore b7ff2e73f692c652
org.junit.jupiter.engine.execution.JupiterEngineExecutionContext d834be9bc6296452
org.junit.jupiter.engine.execution.JupiterEngineExecutionContext.Builder 2e7003b1ba1ccef9
org.junit.jupiter.engine.execution.JupiterEngineExecutionContext.State d08acf502167b7f2
org.junit.jupiter.engine.extension.DisabledCondition 23223b45668b6ef2
org.junit.jupiter.engine.extension.ExtensionRegistry 3bd9c7c773d0274e
org.junit.jupiter.engine.extension.RepeatedTestExtension 1b7914cc8cf83732
org.junit.jupiter.engine.extension.ScriptExecutionCondition 72f1d00f1b0a51e3
org.junit.jupiter.engine.extension.ScriptExecutionCondition.Evaluator 36e29b1b3214594b
org.junit.jupiter.engine.extension.ScriptExecutionEvaluator c2e888183731e173
org.junit.jupiter.engine.extension.TempDirectory 34337e7d3f064058
org.junit.jupiter.engine.extension.TestInfoParameterResolver 1b5b370a56807cae
org.junit.jupiter.engine.extension.TestReporterParameterResolver 60beaf7c80fe99cc
org.junit.jupiter.engine.script.ScriptAccessor.EnvironmentVariableAccessor c0c905d5fe8998ca
org.junit.jupiter.engine.script.ScriptAccessor.SystemPropertyAccessor 18fe4dab72ac1573
org.junit.jupiter.engine.script.ScriptExecutionManager 1f06dfe26cdafe2c
org.junit.jupiter.engine.support.JupiterThrowableCollectorFactory be8bb2befc643502
org.junit.jupiter.engine.support.OpenTest4JAndJUnit4AwareThrowableCollector d5ffe1a3b602d0f0
org.junit.platform.commons.function.Try ed940444537e81c8
org.junit.platform.commons.function.Try.Failure 11c2a90efd237384
org.junit.platform.commons.function.Try.Success c4950437cb3f8d07
org.junit.platform.commons.logging.LoggerFactory 3ba683e3050bf0cd
org.junit.platform.commons.logging.LoggerFactory.DelegatingLogger d773a9f74e627da2
org.junit.platform.commons.util.AnnotationUtils 2bc862bb4af7a8d1
org.junit.platform.commons.util.BlacklistedExceptions bde618675b598c40
org.junit.platform.commons.util.ClassFileVisitor fda6bee00014dc0f
org.junit.platform.commons.util.ClassFilter 093a789d01159576
org.junit.platform.commons.util.ClassLoaderUtils c4b37ecc9a1c73f1
org.junit.platform.commons.util.ClassUtils 8883e6fc8a933271
org.junit.platform.commons.util.ClasspathScanner e023789587082164
org.junit.platform.commons.util.CloseablePath ece3194c27ee878f
org.junit.platform.commons.util.CollectionUtils 795bb2d3912e3e03
org.junit.platform.commons.util.ExceptionUtils 9cd3f0da74956a0f
org.junit.platform.commons.util.Preconditions 3a4283183815a888
org.junit.platform.commons.util.ReflectionUtils 230108a3d8877e27
org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode e8178560b5d6126a
org.junit.platform.commons.util.StringUtils ae2f08e02cb55734
org.junit.platform.commons.util.ToStringBuilder 05623b120035b8d7
org.junit.platform.console.ConsoleLauncher 059adc8d410aa2fd
org.junit.platform.console.ConsoleLauncherExecutionResult 27f4bf4167ea4c68
org.junit.platform.console.options.AvailableOptions fdb77dc12d447dac
org.junit.platform.console.options.CommandLineOptions 7e55c6b93354950a
org.junit.platform.console.options.Details 94f00cde14a89870
org.junit.platform.console.options.DetailsConverter fcf24d774c4b2589
org.junit.platform.console.options.JOptSimpleCommandLineOptionsParser dfe86502b5711f0b
org.junit.platform.console.options.KeyValuePairConverter 6479106b036169b8
org.junit.platform.console.options.Theme efb1fee66cc0d8dc
org.junit.platform.console.options.ThemeConverter 84eb69368d7d50ef
org.junit.platform.console.options.UriConverter da7a6c694ecbadda
org.junit.platform.console.shadow.joptsimple.AbstractOptionSpec 332c05ea73b2a267
org.junit.platform.console.shadow.joptsimple.ArgumentAcceptingOptionSpec e91fb45af3f25527
org.junit.platform.console.shadow.joptsimple.ArgumentList 20a1e6fa7ca1de2f
org.junit.platform.console.shadow.joptsimple.BuiltinHelpFormatter 1f4a9fd151488d57
org.junit.platform.console.shadow.joptsimple.NoArgumentOptionSpec 980fb4b32083f572
org.junit.platform.console.shadow.joptsimple.NonOptionArgumentSpec a6617bf89ff60945
org.junit.platform.console.shadow.joptsimple.OptionParser df3329f5c6910428
org.junit.platform.console.shadow.joptsimple.OptionParserState 46909cb366b4b20d
org.junit.platform.console.shadow.joptsimple.OptionParserState.2 21a8a5a1a79f3845
org.junit.platform.console.shadow.joptsimple.OptionSet 7775c7340e4c9c92
org.junit.platform.console.shadow.joptsimple.OptionSpecBuilder 2ee8eb9f9321ce9e
org.junit.platform.console.shadow.joptsimple.OptionalArgumentOptionSpec 99bf9f189db1b2cb
org.junit.platform.console.shadow.joptsimple.ParserRules 3ad47d297020a97d
org.junit.platform.console.shadow.joptsimple.RequiredArgumentOptionSpec ef502a894c5bf2f7
org.junit.platform.console.shadow.joptsimple.internal.AbbreviationMap 7d8bded7c479d774
org.junit.platform.console.shadow.joptsimple.internal.Classes 29161caedaa4619c
org.junit.platform.console.shadow.joptsimple.internal.MethodInvokingValueConverter c8569bbc8a29f4d9
org.junit.platform.console.shadow.joptsimple.internal.Reflection 7b0a75eb5a86ebd8
org.junit.platform.console.shadow.joptsimple.internal.Rows 03ec8f4347813c4f
org.junit.platform.console.shadow.joptsimple.util.EnumConverter 0585b0c51b5b3266
org.junit.platform.console.shadow.joptsimple.util.KeyValuePair a95c5f7d53974d82
org.junit.platform.console.shadow.joptsimple.util.PathConverter 7204d0c37dbcaa14
org.junit.platform.console.tasks.ConsoleTestExecutor 13bd936b734e2125
org.junit.platform.console.tasks.ConsoleTestExecutor.1 5210c580f0d62985
org.junit.platform.console.tasks.CustomContextClassLoaderExecutor 3f8d889927651162
org.junit.platform.console.tasks.DiscoveryRequestCreator 2406802947cbe928
org.junit.platform.console.tasks.XmlReportData 963ea32e5fdca9d4
org.junit.platform.console.tasks.XmlReportWriter b2e8d74dcd772822
org.junit.platform.console.tasks.XmlReportWriter.TestCounts fb5108b5a5407430
org.junit.platform.console.tasks.XmlReportsWritingListener fd7c2343d2db39e2
org.junit.platform.engine.CompositeFilter ec8dc82249eeb7a9
org.junit.platform.engine.CompositeFilter.1 70825b5141694d2a
org.junit.platform.engine.ExecutionRequest ed3835cc21e5a048
org.junit.platform.engine.Filter f932423ccd3b54bf
org.junit.platform.engine.FilterResult cdaa92f4f6f79059
org.junit.platform.engine.TestDescriptor 9fce516d5ec67d95
org.junit.platform.engine.TestDescriptor.Type 3d400391a113f4d2
org.junit.platform.engine.TestExecutionResult fd67f84654a5aa1c
org.junit.platform.engine.TestExecutionResult.Status 26685ff07ec05579
org.junit.platform.engine.UniqueId 64973686b4e2c690
org.junit.platform.engine.UniqueId.Segment 1872a6198babd9f0
org.junit.platform.engine.UniqueIdFormat 7b04a7efceb2cec1
org.junit.platform.engine.discovery.AbstractClassNameFilter e8b93c76542ae539
org.junit.platform.engine.discovery.ClassNameFilter 61994645098fbceb
org.junit.platform.engine.discovery.ClasspathRootSelector 2e0a9607897269ad
org.junit.platform.engine.discovery.DiscoverySelectors e41af1c3199080ae
org.junit.platform.engine.discovery.IncludeClassNameFilter fb3d2855cc043d05
org.junit.platform.engine.support.descriptor.AbstractTestDescriptor 2bfbf25c43491443
org.junit.platform.engine.support.descriptor.ClassSource 309b80624638115b
org.junit.platform.engine.support.descriptor.EngineDescriptor b7dbf6dfb794516c
org.junit.platform.engine.support.descriptor.MethodSource e28a3ed844bb12d8
org.junit.platform.engine.support.filter.ClasspathScanningSupport eecd7e41276fafb5
org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine 97ffbc145c7d4a83
org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor 68a36544a3925ed3
org.junit.platform.engine.support.hierarchical.LockManager 3b5f78863ff21738
org.junit.platform.engine.support.hierarchical.Node b49761977ceb7101
org.junit.platform.engine.support.hierarchical.Node.SkipResult bd08edf24f1dd4d9
org.junit.platform.engine.support.hierarchical.NodeExecutionAdvisor e5cf54a3abfe8a32
org.junit.platform.engine.support.hierarchical.NodeTestTask 2d78f1925dd4882a
org.junit.platform.engine.support.hierarchical.NodeTestTask.DefaultDynamicTest Executor fdbc89e07549b13b
org.junit.platform.engine.support.hierarchical.NodeTestTaskContext 844fff78e0efe7ef
org.junit.platform.engine.support.hierarchical.NodeTreeWalker b0b50dbbc8c467a5
org.junit.platform.engine.support.hierarchical.NodeUtils d602362461bcf308
org.junit.platform.engine.support.hierarchical.NodeUtils.1 f707e15bc93748e1
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService 054c281153908bb9
org.junit.platform.engine.support.hierarchical.ThrowableCollector 085e5d48a5acd8ee
org.junit.platform.launcher.TestIdentifier 225bb434f8f223e2
org.junit.platform.launcher.TestPlan 9a2b71b572924cbc
org.junit.platform.launcher.core.DefaultDiscoveryRequest 7dda3ad9a0e6a666
org.junit.platform.launcher.core.DefaultLauncher 1a1f88af87dc6ec1
org.junit.platform.launcher.core.ExecutionListenerAdapter 52cf3c3c69d4dfba
org.junit.platform.launcher.core.LauncherConfigurationParameters ef55cacb5e47a902
org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder e78a71b91c159e69
org.junit.platform.launcher.core.LauncherFactory e2bd67b8a72737b5
org.junit.platform.launcher.core.Root 32394ca895f9fb9a
org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry 7c054c4cf76cb0f6
org.junit.platform.launcher.core.ServiceLoaderTestExecutionListenerRegistry 2299bac1075a6bf3
org.junit.platform.launcher.core.TestExecutionListenerRegistry 190f4fb2b0ab865d
org.junit.platform.launcher.core.TestExecutionListenerRegistry.CompositeTestExecutionListener 7538d2d860e1f9cb
org.junit.platform.launcher.listeners.LegacyReportingUtils f3c021e100a54063
org.junit.platform.launcher.listeners.MutableTestExecutionSummary 01ebac90ede3a7fb
org.junit.platform.launcher.listeners.MutableTestExecutionSummary.DefaultFailure e2d08dfc40cdf67e
org.junit.platform.launcher.listeners.SummaryGeneratingListener 2122f1c2f51ec894
org.junit.platform.launcher.listeners.SummaryGeneratingListener.1 e80fbdbe5858ce66
org.opentest4j.AssertionFailedError e810bc40602b9eed
org.opentest4j.ValueWrapper 68056fcd641fcfee
First of all you're using the try/catch structure wrong.
You misuse the exception facility as control structure.
It should be like this:
public void writeObject(Object serObj, String fileName) throws
IOException {
File theFile = new File(filepath + fileName);
if(!theFile.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
try (FileOutputStream fileOut = new FileOutputStream(filepath + fileName);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
objectOut.writeObject(serObj);
}
}
Having this your question changes to: How do I test the if block?
You do this by changing the second parameter of the method from String to File:
public void writeObject(Object serObj, File theFile) throws IOException {
if(!theFile.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
try (FileOutputStream fileOut = new FileOutputStream(filepath + fileName);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
objectOut.writeObject(serObj);
}
}
making the caller of this method responsible for creating the File object.
Then in your test you can pass a mock as this second parameter.
Using Mockito as mocking framework the test would look like this:
class Test {
private String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
#Rule
public final MethodRule mockito = MockitoJunit.rule();
#Spy
private File theFile = new File("data\\test\\" + timeStamp );
#Mock
private File theParent;
#Before
public void setup(){
doReturn(theParent).when(theFile).getParentFile();
}
#Test
void testWriteReadObjectFileNotFound() {
// arrange
doReturn(Boolean.FALSE).when(theFile).exists();
String s1 = "testObj";
// act
wr.writeObject(s1, theFile);
// assert
verify(theParent).mkdirs();
verify.(theFile).createNewFile();
}
}
new FileOutputStream(filepath + fileName) will only throw FileNotFoundException if the specified path is a directory or if a security manager prevents you from writing to that path, as specified in the documentation. If you have right to write to that path, the call will create the file, and no exception will be thrown, explaining why you never enter the block you're referring to.

Java - configure custom loggers for use

Trying to use java.util.logging and failing.
In an attempt to make use of https://stackoverflow.com/a/8249319/3322533 :
handlers = mypackage.logging.RequestFileHandler, mypackage.logging.MainFileHandler
config =
mainLogger.handlers = mypackage.logging.MainFileHandler
requestLogger.handlers = mypackage.logging.RequestFileHandler
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.filter =
java.util.logging.ConsoleHandler.formatter = mypackage.logging.VerySimpleFormatter
java.util.logging.ConsoleHandler.encoding =
mypackage.RequestFileHandler.level = SEVERE
mypackage.RequestFileHandler.filter =
mypackage.RequestFileHandler.formatter = mypackage.logging.VerySimpleFormatter
mypackage.RequestFileHandler.encoding =
mypackage.RequestFileHandler.limit =
mypackage.RequestFileHandler.count =
mypackage.RequestFileHandler.append = false
mypackage.RequestFileHandler.pattern = REQUESTS.%u.%g.log
mypackage.MainFileHandler.level = INFO
mypackage.MainFileHandler.filter =
mypackage.MainFileHandler.formatter = mypackage.logging.VerySimpleFormatter
mypackage.MainFileHandler.encoding =
mypackage.MainFileHandler.limit =
mypackage.MainFileHandler.count =
mypackage.MainFileHandler.append = false
mypackage.MainFileHandler.pattern = MAIN.%u.%g.log
where
public class MainFileHandler extends FileHandler {
public MainFileHandler() throws IOException, SecurityException {
super();
}
}
and
public class RequestFileHandler extends FileHandler {
public RequestFileHandler() throws IOException, SecurityException {
super();
}
}
Intention: provide two loggers accessible through
Logger.getLogger("mainLogger");
or
Logger.getLogger("requestLogger");
respectively, one that will write (exclusively) to MAIN[...].log and the other to REQUESTS[...].log
(No limits on the amount of messages that can be logged to either file and if necessary, use logging level to filter out unwanted msgs to either.)
However, neither file is created when I (for example)
public static final Logger log = Logger.getLogger("mainLogger");
and then
public void configureLogger(){
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream config = classLoader.getResourceAsStream("logging.properties");
LogManager.getLogManager().readConfiguration(config);
}catch(Exception ex){
throw new RuntimeException("logging properties failed");
}
}
before I
log.info("Hello World!")
I know the properties are loaded because when I include java.util.logging.ConsoleHandler in the handlers = ... list and use the global logger, instead, the formatter is applied for the console output.
So ... I guess my attempt at setting up the file loggers is faulty. How do I get this working?
EDIT
So I removed the [...].pattern = [...] lines and instead hardcoded the file names:
public class MainFileHandler extends FileHandler implements FileHandlerProperties {
public MainFileHandler() throws IOException, SecurityException {
super("MAIN_" + new SimpleDateFormat(TIME_PATTERN).format(new Date()) + ".log");
}
}
and
public class RequestFileHandler extends FileHandler implements FileHandlerProperties {
public RequestFileHandler() throws IOException, SecurityException {
super("REQUESTS_" + new SimpleDateFormat(TIME_PATTERN).format(new Date()) + ".log");
}
}
where
public interface FileHandlerProperties {
static final String TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
}
Both files now get created BUT they both contain exactly the same (despite their different level settings and loggers) AND what they contain is in xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2016-10-10T18:49:23</date>
<millis>1476118163654</millis>
<sequence>0</sequence>
<logger>mainLogger</logger>
<level>INFO</level>
<class>mypackage.main.Main</class>
<method><init></method>
<thread>1</thread>
<message>Hello World</message>
</record>
</log>
Please help ...
The problem is that the first call to Logger.getLogger during class loading reads the log configuration and your configureLogger method fails due to JDK-8033661: readConfiguration does not cleanly reinitialize the logging system.
To workaround this you have to ensure that configureLogger runs before the first call to Logger.getLogger.
public class BootMain {
static {
configureLogger();
mainLogger = Logger.getLogger("mainLogger");
requestLogger = Logger.getLogger("requestLogger");
}
private static final Logger mainLogger;
private static final Logger requestLogger;
public static void main(String[] args) throws IOException {
mainLogger.log(Level.SEVERE, "Test from main.");
requestLogger.log(Level.SEVERE, "Test from request.");
System.out.println(new File(".").getCanonicalPath());
}
private static void configureLogger() {
try {
InputStream config = config();
LogManager.getLogManager().readConfiguration(config);
} catch (Exception ex) {
throw new RuntimeException("logging properties failed");
}
}
private static String prefix() {
return "mypackage.logging";
}
private static InputStream config() throws IOException {
String p = prefix();
Properties props = new Properties();
props.put("mainLogger.handlers", p + ".MainFileHandler");
props.put("requestLogger.handlers", p + ".RequestFileHandler");
props.put(p + ".RequestFileHandler.level", "SEVERE");
props.put(p + ".MainFileHandler.level", "INFO");
props.put(p + ".RequestFileHandler.pattern", "REQUESTS.%u.%g.log");
props.put(p + ".MainFileHandler.pattern", "MAIN.%u.%g.log");
ByteArrayOutputStream out = new ByteArrayOutputStream();
props.store(out, "");
return new ByteArrayInputStream(out.toByteArray());
}
}
Also make sure you are not using a really old version of JDK or you can run into JDK-5089480: java.util.logging.FileHandler uses hardcoded classname when reading properties.
Otherwise you can use the LogManager config option to manually setup your configuration.

com.netflix.hystrix.exception.HystrixRuntimeException: execute timed-out and no fallback available

I am writing an test class for Integration Testing using groovy file
My Groovy File :
#UseModules(value = [MiddleModule])
class MiddleServiceIT extends Specification{
#Inject
MiddleService middleService
#Rule
public WireMockRule Server = new WireMockRule(wireMockConfig().port(9090));
def 'validate config'() {
expect:
middleService != null
}
def 'validate get'() {
/* String urlPath = 'http://localhost:8889/middle/?acctID=80873000101&vodSource=ais&headendID=louis&activeOnly=true&limit=50&startDate=2014-10-09&inclNonSyncData=test' */
String urlPath = 'http://localhost:8889/middle/'
given:
Server.stubFor(get(urlPathEqualTo(urlPath)).willReturn(MiddleServiceStub.buildSuccess()))
when:
MiddleMessage response = middleService.get( '80873000101','ais', 'louis', 'true', '50', '2014-10-09', 'test')
then:
response != null
}
}
Here my requirement is when it hits that URL, it has to give the response which I mentioned in the stubFor call.
My Original Method :
#Override
public MiddleMessage get(String acctID, String vodSource, String headendID, String activeOnly, String limit, String startDate, String inclNonSyncData){
String url = rentalsMiddleBaseUrl + "/?acctID=" + acctID + "&vodSource=" + vodSource + "&headendID=" + headendID + "&activeOnly=" + activeOnly + "&limit=" + limit + "&startDate=" + startDate + "&inclNonSyncData=" + inclNonSyncData;
System.out.println("***** For Test URL "+url);
return (MiddleMessage) commandBuilder.build(url,MiddleMessage.class).execute();
}
My Stub Method in MiddleServiceStub Class:
public static ResponseDefinitionBuilder buildSuccess() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MiddleSet middleSet = new MiddleSet();
MiddleMessage middleMessage = new MiddleMessage();
middleMessage.setMiddleSet(middleSet);
String json = mapper.writeValueAsString(middleMessage);
ResponseDefinitionBuilder responseDefinitionBuilder = ResponseDefinitionBuilder.like(ResponseDefinition.created()).withBody(json);
return responseDefinitionBuilder;
}
When I run the above code using maven command "clean install" it is giving the following exception
validate get(com.config.MiddleServiceTest) Time elapsed: 1.918 sec <<< ERROR!
com.netflix.hystrix.exception.HystrixRuntimeException: execute timed-out and no fallback available.
at com.netflix.hystrix.HystrixCommand.getFallbackOrThrowException(HystrixCommand.java:1646)
at com.netflix.hystrix.HystrixCommand.access$1900(HystrixCommand.java:103)
at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$1.run(HystrixCommand.java:1023)
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41)
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37)
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57)
at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$2.tick(HystrixCommand.java:1047)
at com.netflix.hystrix.HystrixCommand$1.performBlockingGetWithTimeout(HystrixCommand.java:627)
at com.netflix.hystrix.HystrixCommand$1.get(HystrixCommand.java:522)
at com.netflix.hystrix.HystrixCommand.execute(HystrixCommand.java:431)
at com.client.MiddleService.get(MiddleService.java:72)
at com.config.MiddleServiceTest.validate get(MiddleServiceTest.groovy:22)
Caused by: java.util.concurrent.TimeoutException
The parameter you pass to urlPathEqualTo(...) should be a relative URL, not absolute.
I don't know if this is what's causing the exception you've pasted, but WireMock will return a 404 given your current setup, which I suspect isn't what you want.

Categories

Resources