How do you unit test mongo-hadoop jobs?
My attempt so far:
public class MapperTest {
MapDriver<Object, BSONObject, Text, IntWritable> d;
#Before
public void setUp() throws IOException {
WordMapper mapper = new WordMapper();
d = MapDriver.newMapDriver(mapper);
}
#Test
public void testMapper() throws IOException {
BSONObject doc = new BasicBSONObject("sentence", "Two words");
d.withInput(new Text("anykey"), doc );
d.withOutput(new Text("Two"), new IntWritable(1));
d.withOutput(new Text("words"), new IntWritable(1));
d.runTest();
}
}
Which produces this output:
No applicable class implementing Serialization in conf at io.serializations for class org.bson.BasicBSONObject
java.lang.IllegalStateException
at org.apache.hadoop.mrunit.internal.io.Serialization.copy(Serialization.java:67)
at org.apache.hadoop.mrunit.internal.io.Serialization.copy(Serialization.java:91)
at org.apache.hadoop.mrunit.internal.io.Serialization.copyWithConf(Serialization.java:104)
at org.apache.hadoop.mrunit.TestDriver.copy(TestDriver.java:608)
at org.apache.hadoop.mrunit.TestDriver.copyPair(TestDriver.java:612)
at org.apache.hadoop.mrunit.MapDriverBase.addInput(MapDriverBase.java:118)
at org.apache.hadoop.mrunit.MapDriverBase.withInput(MapDriverBase.java:207)
...
You need to set the serializer.
Example : mapDriver.getConfiguration().setStrings("io.serializations",
"org.apache.hadoop.io.serializer.WritableSerialization", MongoSerDe.class.getName());
MongoSerDe src: https://gist.github.com/lfrancke/01d1819a94f14da171e3
But I face error "org.bson.io.BasicOutputBuffer.pipe(Ljava/io/DataOutput;)I" while using this(MongoSerDe).
Related
I have the following implementation to create QR Code and try to return generated code as html response (ask user to open or save the generated image) instead of saving to file in a directory. However, I could not manage to perform that. I use the following example on Baeldung: https://www.baeldung.com/java-generating-barcodes-qr-codes
public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix =
barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
I use the following REST Controller method:
#RestController
#RequestMapping("/barcodes")
public class BarcodesController {
#GetMapping(value = "/barbecue/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> barbecueEAN13Barcode(#PathVariable("barcode") String barcode)
throws Exception {
return okResponse(BarbecueBarcodeGenerator.generateEAN13BarcodeImage(barcode));
}
//...
}
However, I cannot get the image as HTTP response. So, how can I fix it?
Update: Here is my Application.java:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
#Bean
public HttpMessageConverter<BufferedImage> createImageHttpMessageConverter() {
return new BufferedImageHttpMessageConverter();
}
}
Is that enough? Or should I call it from anywhere?
I am running through some exercises on https://spring.io/ Spring Boot.
Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7. I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).
Application.java
#SpringBootApplication
#EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
return (args) -> errors out saying "use source -8 or higher to enable
lambda expressions"
FileUploadController.java
import java.util.stream.Collectors
//..
#GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
package java.util.stream does not exist
type loadAll() is erroneous
errors out saying "use source -8 or higher to enable
lambda expressions"
FileSystemStorageService.java
#Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
cannot find symbol walk
errors out saying "use source -8 or higher to enable
lambda expressions"
StorageService.java
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
package java.util.stream does not exist
Bulltorious, I'm sorry for your bounty but you really have only very few choices. Stream API was added only in Java 8 and thus does not exist in the Java 7. You can work-around lambda-related issues by manually writting anonymous classes or even almost automatically (see Retrolambda). However with the Stream API you only have two choices:
Backport Stream API to Java 7 manually. Or use someone else attempt to backport such as streamsupport project on SourceForge (or copy on GitHub)
Get rid of the Stream API and use older Java 7 classes.
Update (replace Files.walk)
In case your Files.walk is the only place you use Java-8-specific API, you can replace it with Java 7 API relatively easily:
interface PathNameMapper
{
String mapPath(Path path);
}
List<String> loadAll(PathNameMapper mapper)
{
try
{
List<String> result = new ArrayList<>();
Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>()
{
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
if (!rootLocation.equals(file))
{
result.add(mapper.mapPath(rootLocation.relativize(file)));
}
return FileVisitResult.CONTINUE;
}
});
return result;
}
catch (IOException e)
{
throw new StorageException("Failed to read stored files", e);
}
}
and then your listUploadedFiles would become something like
#GetMapping ("/")
public String listUploadedFiles(Model model) throws IOException
{
model.addAttribute("files", storageService
.loadAll(new PathNameMapper()
{
#Override
public String mapPath(Path path)
{
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString();
}
}));
return "uploadForm";
}
Update 2 (labmda -> anonymous class conversion)
And just for completeness an example of how to convert lambda to an anonymous class manually:
#Bean
CommandLineRunner init(StorageService storageService)
{
return new CommandLineRunner()
{
#Override
public void run(String... args) throws Exception
{
storageService.deleteAll();
storageService.init();
}
};
}
You can update your methods like below to Java 7 variant. All the test cases are passing.
Application.java
#SpringBootApplication
#EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
#Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
FileUploadController.java
#GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
Updated the method implementation to use DirectoryStream to simple listing all the files.
FileSystemStorageService.java
#Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
StorageService.java
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
FileUploadTests
#Test
public void shouldListAllFiles() throws Exception {
given(this.storageService.loadAll())
.willReturn(Arrays.asList(Paths.get("first.txt"), Paths.get("second.txt")));
this.mvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(model().attribute("files",
Matchers.contains("http://localhost/files/first.txt", "http://localhost/files/second.txt")));
}
FileSystemStorageServiceTest
#RunWith(SpringRunner.class)
#SpringBootTest
public class FileSystemStorageServiceTest {
#Autowired
private StorageService storageService;
#Test
public void loadAll() throws Exception {
MockMultipartFile multipartFile =
new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes());
storageService.store(multipartFile);
List<Path> paths = storageService.loadAll();
assertThat(paths.size()).isEqualTo(1);
}
}
Update TestCompare with rootLocation set to FileSystems.getDefault().getPath(".")
#RunWith(SpringRunner.class)
public class TestCompare {
#Configuration
#ComponentScan(basePackages = {"hello.storage"})
#EnableConfigurationProperties(StorageProperties.class)
static class ContextConfiguration{}
#Autowired
private StorageService storageService;
#Test
public void loadAllDirectoryStreamVsloadAllWalkFileWithDepth1() throws Exception {
List<Path> paths1 = storageService.loadAllDirectoryStream();
List<Path> paths2 = storageService.loadAllWalkFileWithDepth1();
assertThat(paths1.size()).isEqualTo(paths2.size());
}
}
I've added two methods just for testing purposes. One using DirectoryStream and another using WalkFileTree with maxDepth set to 1. Both of them works the same.
#Override
public List<Path> loadAllDirectoryStream() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
//if(!Files.isDirectory(entry))
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
#Override
public List<Path> loadAllWalkFileWithDepth1() {
List<Path> rPaths = new ArrayList<>();
try {
Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!rootLocation.equals(file)) {
rPaths.add(rootLocation.relativize(file));
}
return FileVisitResult.CONTINUE;
}
});
return rPaths;
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
Building on SergGr's and Veeram's excellent answers I'll show an alternative implementation of the two critical methods that depend on the Java 8 Stream API (loadAll() and listUploadedFiles()) using the streamsupport backport of the Stream API already mentioned in SergGr's answer.
This implementation doesn't use lambdas (though that could easily be done using retrolambda) because it is probably overkill to introduce retrolambda for only a couple of lambda expressions.
FileSystemStorageService.java
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
#Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
#Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
#Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
#Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
FileUploadController.java
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
#GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
pom.xml
<dependency>
<groupId>net.sourceforge.streamsupport</groupId>
<artifactId>streamsupport</artifactId>
<version>1.5.4</version>
</dependency>
Hope this helps you get going. Disclaimer: Note that I haven't tested this!
The lambdas are in fact single-method interfaces, called functional interfaces. You can easily convert most of lambda expression to interface simply by following your IDE code completions. For example, let's take a filter method:
filter(Predicate<? super T> predicate)
As you can see, filter method simply accepts an instance of Predicate interface, which has test method that looks like this:
boolean test(T t)
Evaluates this predicate on the given argument.
Parameters:
t - the input argument
Returns:
true if the input argument matches the predicate, otherwise false
You can easily create your own Predicate implementation and use it while iterating your examples. For instance, you can create your own generic filter method which takes a Collection and your predicate strategy which will be applied for every element. You can also use Guava Function interfaces, which were used before Java 8. Here you have some explanation how to use it: https://github.com/google/guava/wiki/FunctionalExplained.
To sum it up - you can use Guava or create your own wrappers for every example. You can simulate streams simply by iterating your collections. Converting lambdas is a no-brainer, since you realize they are just single-method interfaces.
Hi I am working on a project and using PrintWriter class for opening and writing in the file. But when I am writing the test case for same it gives following error at Line 153
Wanted but not invoked:
mockPrintWriter.println("ID url1
");
-> at x.y.z.verify(ProcessImageDataTest.java:153)
Actually, there were zero interactions with this mock.
Code: (Uses Lombok Library)
ProcessImageData.java
#Setter
#RequiredArgsConstructor
public class ProcessImageData implements T {
private final File newImageDataTextFile;
#Override
public void execute() {
LineIterator inputFileIterator = null;
try {
File filteredImageDataTextFile = new File(filteredImageDataTextFilepath);
PrintWriter writer = new PrintWriter(newImageDataTextFile);
inputFileIterator = FileUtils.lineIterator(filteredImageDataTextFile, StandardCharsets.UTF_8.displayName());
while (inputFileIterator.hasNext()) {
if(someCondition)
**Line51** writer.println(imageDataFileLine);
//FileUtils.writeStringToFile(newImageDataTextFile, imageDataFileLine + NEWLINE, true);
}
}
} catch (Exception e) {
} finally {
LineIterator.closeQuietly(inputFileIterator);
**LINE63** writer.close();
}
}
ProcessImageDataTest.java
#RunWith(PowerMockRunner.class)
#PrepareForTest({ ProcessImageData.class, FileUtils.class, Printwriter.class })
public class ProcessImageDataTest {
private ProcessImageData processImageData;
private static final String FILTERED_IMAGE_DATA_TEXT_FILE_PATH = "filteredFilepath";
private File FILTEREDFILE = new File(FILTERED_PATH);
private static final File IMAGE__FILE = new File("imageFilePath");
private LineIterator lineIterator;
#Mock
private PrintWriter mockPrintWriter;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
processImageData = new ProcessImageData(Palettes_file, FILTERED_PATH, IMAGE_FILE);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE).thenReturn(mockPrintWriter);
PowerMockito.when(FileUtils.lineIterator(FILTERED_FILE, StandardCharsets.UTF_8.displayName())).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
}
#Test
public void testTaskWhenIDInDBAndStale() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID1 + SPACE + URL2);
processImageData.execute();
List<String> exepctedFileContentOutput = Arrays.asList(ID2 + SPACE + URL1 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}
#Test
public void testTaskWhenIDNotInDB() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID3 + SPACE + URL2);
processImageData.execute();
List<String> exepctedFileContentOutput = Arrays.asList(ID3 + SPACE + URL2 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}
private void verify(List<String> exepctedFileContentOutput, int fileWriteTimes, int fileReadTimes) throws IOException {
for (String line : exepctedFileContentOutput){
**Line153** Mockito.verify(mockPrintWriter, Mockito.times(fileWriteTimes)).print(line);
}
PowerMockito.verifyStatic(Mockito.times(fileReadTimes));
FileUtils.lineIterator(FILTERED_IMAGE_DATA_TEXT_FILE, StandardCharsets.UTF_8.displayName());
}
}
I am mocking a new operator for PrintWriter also, injecting using beans. What is the mistake I am doing?? I am stuck on it from long time and not getting the error?
Any help is appreciated.
Updated :
I did changes suggested below and updated the code, but now I get the error:
Wanted but not invoked: mockPrintWriter.print("ASIN2 url1 "); ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageDataTest.verify(ProcessImageDataTest.java:153)
However, there were other interactions with this mock: -> at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(ProcessImageData.java:51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(ProcessImageData.java:51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(ProcessImageData.java:58) –
I see 3 issues in your test:
You don't try to mock the correct constructor, indeed in the method execute, you create your PrintWriter with only one argument of type File while you try to mock the constructor with 2 arguments one of type File and the other one of type String.
So the code should rather be:
PowerMockito.whenNew(PrintWriter.class)
.withArguments(IMAGE_FILE)
.thenReturn(mockPrintWriter);
To be able to mock a constructor you need to prepare the class creating the instance which is ProcessImageData in this case, so you need to add ProcessImageData.class in the annotation #PrepareForTest. (I'm not sure ProcessImageDataTest.class is needed there)
The field lineIterator should be annotated with #Mock.
Instead of verifying print with a new line, you should verify directly println without new line it is much less error prone.
I simplified your code to show the idea.
Assuming that ProcessImageData is:
public class ProcessImageData {
private final File newImageDataTextFile;
public ProcessImageData(final File newImageDataTextFile) {
this.newImageDataTextFile = newImageDataTextFile;
}
public void execute() throws Exception{
try (PrintWriter writer = new PrintWriter(newImageDataTextFile)) {
LineIterator inputFileIterator = FileUtils.lineIterator(
newImageDataTextFile, StandardCharsets.UTF_8.displayName()
);
while (inputFileIterator.hasNext()) {
writer.println(inputFileIterator.nextLine());
}
}
}
}
My unit test would then be:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ProcessImageData.class, FileUtils.class})
public class ProcessImageDataTest {
private File file = new File("imageFilePath");
private ProcessImageData processImageData;
#Mock
private PrintWriter mockPrintWriter;
#Mock
private LineIterator lineIterator;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
processImageData = new ProcessImageData(file);
PowerMockito.whenNew(PrintWriter.class)
.withArguments(file)
.thenReturn(mockPrintWriter);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.when(
FileUtils.lineIterator(file, StandardCharsets.UTF_8.displayName())
).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
}
#Test
public void testExecute() throws Exception {
PowerMockito.when(lineIterator.nextLine()).thenReturn("Foo", "Bar");
processImageData.execute();
Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Foo");
Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Bar");
}
}
For more details please refer to How to mock construction of new objects.
how can I add verification in unit test for writer.close?
One way could be to simply check that close() at be called once by adding the next line to your unit test:
Mockito.verify(mockPrintWriter, Mockito.times(1)).close();
Your construction of the PrintWriter doesn't match the mock. You told PowerMockito to return your mock like this:
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE , StandardCharsets.UTF_8.name()).thenReturn(mockPrintWriter);
So you would have to say:
new PrintWriter(IMAGE_FILE, "UTF-8"); // 2 arguments
But instead in your execute method in the code that is being tested, you do:
PrintWriter writer = new PrintWriter(newImageDataTextFile); // only 1 argument
So you either need to change the PowerMockito withArguments clause, or you need to add "UTF-8" to the constructor invocation in the execute method.
This is my code:
public void analyze(String url) throws SiteBusinessException {
Document doc = null;
Response response = null;
try {
response = Jsoup.connect(url).execute();
doc = Jsoup.connect(url).get();
} catch (IOException e) {
LOGGER.warn("Cannot analyze site [url={}, statusCode={}, statusMessage={} ]", new Object[] {url, response.statusCode(), response.statusMessage()});
throw new SiteBusinessException(response.statusMessage(), String.valueOf(response.statusCode()));
}
}
How can I test this method using PowerMock? I want to write test to check that when invoke .execute() then throw IOException and it catch then throw SiteBusinessException.
My code of test.
#RunWith(PowerMockRunner.class)
#PrepareForTest({Jsoup.class})
Test(expected = SiteBusinessException.class)
public void shouldThrowIOException() throws Exception {
Connection connection = PowerMockito.mock(Connection.class);
Response response = PowerMockito.mock(Response.class);
PowerMockito.when(connection.execute()).thenReturn(response);
PowerMockito.mockStatic(Jsoup.class);
expect(Jsoup.connect(SITE_URL)).andReturn(connection);
replay(Jsoup.class);
PowerMockito.when(Jsoup.connect(SITE_URL).execute()).thenThrow(new IOException());
AnalyzerService sut = new AnalyzerServiceImpl();
sut.analyzeSite(SITE_URL);
}
I got
java.lang.Exception: Unexpected exception, expected<com.siteraport.exception.SiteBusinessException> but was<java.lang.IllegalStateException>
??
You need to create a static mock of the Jsoup class. Once you have created such a mock in your test case, you can code your expectations using it.
Please see mock static method using PowerMockito documentation.
Here the Testcase using Mockito and PowerMockito:
I was able to mock the execute method using Mockito + Powermockito (you are using both EasyMock and Mockito?) The code in the test case looks as below:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Jsoup.class})
public class MyClassTest {
#Test(expected = SiteBusinessException.class)
public void shouldThrowIOException() throws Exception {
String SITE_URL = "some_url_string";
Connection connection = Mockito.mock(Connection.class);
Mockito.when(connection.execute()).thenThrow(new IOException("test"));
PowerMockito.mockStatic(Jsoup.class);
PowerMockito.when(Jsoup.connect(Mockito.anyString())).
thenReturn(connection);
AnalyzerService sut = new AnalyzerService();
sut.analyze(SITE_URL);
}
}
I try to create a soap UI WSDL Mock Service using the soapUI API. But there seems to be no documentation of the source code.
Has anyone done this before or something in that direction?
Ok, I can now answer myself ... :)
I created a unit test for this task:
private static WsdlProjectFactory wsdlProjectFactory;
private static WsdlInterfaceFactory wsdlInterfaceFactory;
#BeforeClass
public static void createFactories(){
wsdlProjectFactory = new WsdlProjectFactory();
wsdlInterfaceFactory = new WsdlInterfaceFactory();
}
#Before
public void deleteCreatedFiles() {
new File("global-groovy.log").delete();
new File("soapui-errors.log").delete();
new File("soapui.log").delete();
new File("test.xml").delete();
}
private WsdlProject project;
#Before
public void createProject() throws XmlException, IOException, SoapUIException {
project = wsdlProjectFactory.createNew();
}
#Test #Ignore
public void testWSDLInterfaceImporting() throws SoapUIException {
int interfaceCount = project.getInterfaceCount();
assertThat("newly created project has no interfaces", interfaceCount, is(equalTo(0)));
WsdlInterface[] importWsdl = wsdlInterfaceFactory.importWsdl(project, "wsdls/SimpleUseCasesellerbtainitialbtexampleMasterClient.wsdl", false);
interfaceCount = project.getInterfaceCount();
assertThat("newly created project has 1 interface", interfaceCount, is(equalTo(1)));
}
#Test
public void testMockCreation() throws XmlException, IOException, SoapUIException {
int mockCount = project.getMockServiceCount();
assertThat("newly created project has no mocks", mockCount, is(equalTo(0)));
WsdlInterface[] importWsdl = wsdlInterfaceFactory.importWsdl(project, "wsdls/SimpleUseCasesellerbtainitialbtexampleMasterClient.wsdl", false);
WsdlMockService service = project.addNewMockService("newMockService");
service.addNewMockOperation(importWsdl[0].getOperationAt(0));
project.saveAs("test.xml");
mockCount = project.getMockServiceCount();
assertThat("project has exactly one mock", mockCount, is(1));
}