I would like to mock the make a JUnit test of the following method toXml:
void toXml(Object obj){
ByteArrayOutputStream out = null;
try{
JAXBContext ctx = getContext(obj.getClass());
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setAttachmentMarshaller(new AttachmentMarshallerImpl());
out = new ByteArrayOutputStream();
marshaller.marshal( obj, out );
}catch( JAXBException e ){
throw new RuntimeException("Problem in parsing", e);
}
}
I have tried the following:
#Test
public void testToXml() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
SystemPointDto systemPointDto = new SystemPointDto();
verify((marshaller), atLeast(1)).marshal(systemPointDto, out);
}
However I am getting a NullPointerException when I run the test. I am a newbie in testing probably the answer is very easy. Could you please advice? Thanks in advance.
EDIT:
The mocking code as asked in the comments is:
#Mock
AttachmentMarshallerImpl attachmentMarshaller;
#InjectMocks
Marshaller marshaller;
And this is the stack trace:
initMocks(TestingIfTheMarshalGetsCalledWithoutExceptionTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Caused by: org.mockito.exceptions.base.MockitoException: the type 'Marshaller' is an interface.
... 32 more
In your Method you get the Marshaller from a JAXBContext. To use your mock Marshaller, your need a JAXBContext that returns the mock when createMarshaller is called.
assuming the following class under test:
public class XmlMarshaller {
private JAXBContextFactory contextFactory;
public XmlMarshaller(JAXBContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
private JAXBContext getContext(Class<?> type) {
return contextFactory.get(type);
}
public void toXml(Object obj){
// ... your code
}
}
your test setup would need to look like this:
public class XmlMarshallerTest {
#Mock
JAXBContext ctx;
#Mock
Marshaller marshaller;
#Mock
JAXBContextFactory factory;
#InjectMocks
XmlMarshaller classUnderTest;
#Before
public void setup() {
MockitoAnnotations.initMocks(this); // creates mocks and injects the as needed into the classUnderTest
when(ctx.createMarshaller()).thenReturn(marshaller);
}
#Test
public void toXmlCallsJAXBMarshaller() {
when(factory.get(SystemPointDto.class)).thenReturn(ctx);
SystemPointDto systemPointDto = new SystemPointDto();
classUnderTest.toXml(systemPointDto);
verify(marshaller).marshal(eq(systemPointDto), any(ByteArrayOutputStream.class));
}
}
Related
This function tries to retrieve the topic of the GitHub repository name using the GitHub API: https://api.github.com/repos/flutter/flutter/topics
public List<String> getTopics(SearchRepository searchRepository){
GitHubRequest request = new GitHubRequest();
List<String> topic_list = new ArrayList<>();
try {
String url = searchRepository.getUrl().split("//")[1].split("github.com")[1];
request.setUri("/repos"+ url + "/topics");
String result = new BufferedReader(new InputStreamReader(gitHubClient.getStream(request)))
.lines().collect(Collectors.joining("\n"));
JSONObject jsonObject = new JSONObject(result);
topic_list = Arrays.stream(jsonObject.get("names").toString().replace("[", "").replace("]", "").split(",")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return topic_list;
}
The url returned before string to list conversion is :https://github.com/repouser/reponame
SearchRepository is the v2 model class of Repository from the package:
SearchRepositroy
As per the earlier suggestions from this wonderful community answers (though the question is now edited, it remains yet relevant) I created the mock test to test the above function as below:
#Test
public void getTopicsTest() throws IOException{
SearchRepository mocksearchRepository = mock(SearchRepository.class);
GitHubClient mockClient = mock(GitHubClient.class);
GitHubRequest mockRequest = mock(GitHubRequest.class);
when(mocksearchRepository.getUrl()).thenReturn("https://github.com/mockuser/mockrepo");
when(mocksearchRepository.getName()).thenReturn("mockrepo");
when(mocksearchRepository.getOwner()).thenReturn("mockuser");
//when(mockRequest.setUri((String) any())).thenReturn(mockRequest.setUri("/repo/mockuser/mockrepo/topics"));
//The format of the return form is: https://github.com/CyC2018/CS-Notes
when(mockClient.getStream(any())).thenReturn(topicInputStream());
//SearchRepository querySearch = new SearchRepository("mockuser","mockrepo");
List<String> topics = githubServiceMock.getTopics(mocksearchRepository);
System.out.println(topics);
}
private InputStream topicInputStream() {
String mockTopics = "{" +
"topic1\": [" +
"topic2\"," +
"topic3\"," +
"skia" +
"]" +
"}";
InputStream stream = new ByteArrayInputStream(mockTopics.getBytes(StandardCharsets.UTF_8));
System.out.println(stream);
return stream;
}
However, I get the 404 internal server error Exception due to the request.setUri(Uri(String)) in the function. Please suggest where I am going wrong.
Test services.GithubServiceTest.getTopicsTest started
java.io.ByteArrayInputStream#6ed99482
org.eclipse.egit.github.core.client.RequestException: Not Found (404)
| => rat org.eclipse.egit.github.core.client.GitHubClient.createException(GitHubClient.java:552)
at org.eclipse.egit.github.core.client.GitHubClient.getResponseStream(GitHubClient.java:701)
at org.eclipse.egit.github.core.client.GitHubClient.getStream(GitHubClient.java:667)
at services.GithubService.getTopics(GithubService.java:231)
at services.GithubServiceTest.getTopicsTest(GithubServiceTest.java:222)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at com.novocode.junit.JUnitRunner$1.execute(JUnitRunner.java:132)
at sbt.ForkMain$Run.lambda$runTest$1(ForkMain.java:413)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
[]
[info] Test services.GithubServiceTest.getIssueWordLevelStatisticsTest started
[info] Test services.GithubServiceTest.getRepositoriesByTopicTest started
[info] Test services.GithubServiceTest.getUserDetailsTest started
[info] Test services.GithubServiceTest.getRepositoryDetailsTest started
[info] Test run finished: 0 failed, 0 ignored, 5 total, 1.122s
[error] Failed: Total 10, Failed 1, Errors 0, Passed 9
[error] Failed tests:
[error] controllers.GithubControllerTest
[error] (Test / test) sbt.TestsFailedException: Tests unsuccessful
You can mock repositoryService and gitHubClient to test various scenarios.
You can provide a package-level setter for these fields. It is a great idea to annotate it with Guava VisibleForTesting annotation.
Then you need to set mocks before the actual test on the instance.
Pseudocode for mocking
// First, we mock repository so we can return it from service
Repository repositoryMock = mock(Repository.class);
when(repository.getUrl()).thenReturn("https://...."); // You can return a URL or String, according to the mocked method's return type
// Then, we mock RepositoryService as well
RepositoryService repositoryServiceMock = mock(RepositoryService.class);
when(repositoryServiceMock.getRepository(anyString(), anyString()).thenReturn(repositoryMock);
// We mock gitHubService similarly
...
// After setting mock on the instance, we call the method and see if the results are expected
List<String> topics = getTopics("...", "...");
assertEquals(topics, ...);
// You can also assert interaction related things
verify(repositoryService).getRepository("a", "b"); // This is OK only if the service is called with "a" and "b" arguments
First, you need to inject the mock object (repositoryService,gitHubClient) to your function.
If you use spring/spring boot, you can consider to use #Mock and #MockBean annotation.
to mock the necessary bean.
The below code to create mock object manually.
RepositoryService fakeRs = Mockito.mock(RepositoryService.class);
GitHubClient fakeGHC = Mockito.mock(GitHubClient.class);
You also can use setter method to set mock object.
setRepositoryService(fakeRs);
setGitHubClient(fakeGHC);
The other way is using reflection utility to set private object.
ReflectionTestUtils.setField(yourService, "repositoryService", fakeRs);
ReflectionTestUtils.setField(yourService, "gitHubClient", fakeGHC);
After finish ingesting the mock object, you can write an test with expected behavior/data from mock object.
#Test
public void testGetTopics(){
// init mock object code in case setter/getter/reflection utils
Repository expectedRepository = createExampleRepository();
Mockito.when(repositoryService.getRepository(Mockito.anyString(),Mockito.anyString())
.thenReturn(expectedRepository);
// continue to fake gitHubClient with your expected data/ exceptions...
//call your method
List<?> data = yourService.getTopic("user","data");
Assertions.assertTrue(data!=null);
// you can write few assertion base on your fake datas
}
PS: Don't copy/paste the code, you will get compile errors. I am not using editor tool.
How do I resolve this NullPointerException ?
A little background , I am developing a Spring based Project and using HibernateTemlate in DAO layer to do all database related operations.
here is the snippet of code which i have extracted out of my test class which is throwing NullPointerException.
try {
List<Object[]> list = (List<Object[]>) ht.find("select uomId,uomModel from in.nit.model.Uom");
System.out.println(list);
}catch(NullPointerException e) {
e.printStackTrace();
}
And this is the stacktrace of the exception on the console.
```
java.lang.NullPointerException
at in.nit.dao.impl.UomDaoImplTest.test(UomDaoImplTest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
```
Here is my model class
```
#Entity
#Table(name="uomtab")
public class Uom {
#Id #GeneratedValue #Column(name="umid") private Integer uomId;
#Column(name="utype") private String uomType;
#Column(name="umodel") private String uomModel;
#Column(name="udesc") private String uomDesc;
public Uom() {
super();
}
public Uom(Integer uomId) {
this.uomId = uomId;
}
public Integer getUomId() {
return uomId;
}
public void setUomId(Integer uomId) {
this.uomId = uomId;
}
public String getUomType() {
return uomType;
}
public void setUomType(String uomType) {
this.uomType = uomType;
}
public String getUomModel() {
return uomModel;
}
public void setUomModel(String uomModel) {
this.uomModel = uomModel;
}
public String getUomDesc() {
return uomDesc;
}
public void setUomDesc(String uomDesc) {
this.uomDesc = uomDesc;
}
#Override
public String toString() {
return "Uom [uomId=" + uomId + ", uomType=" + uomType + ", uomModel=" + uomModel + ",
uomDesc=" + uomDesc + "]";
}
}
```
Also even though the find(String Query) method is deprecated,I have extensively used it in other dao classes of my project which works smooth and fine.
What could be the possible reasons for this exception blowing up my code?
You shouldn't catch that NullPointerException
What is line 28 in your code?
Did you try and debug the line? If it is the ht.find line, the only thing that makes sense is that your HibernateTemplate is null and has not been set correctly.
your error is in class "UomDaoImplTest". That has no relation with Hibernate Template.
can you post your test class.
Hi So I'm new to Junit and Mockito, so please bare with some misconception/mistakes that Ive made. I have a springbott service that I wanted to test and I want to mock a method call that is being made in one of the methods that I am testing but It will not work for some reason. I used both when(xxx.method(anyArgs)).return(someData) as well as doReturn(someData).when(xxx).method(anyArgs); But I still get the same type of error: InvalidUseOfMatchersException. I mock the service layer but I can not figure out what causes the issue.
The Exact Stack Trace:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
My Service Layer Code:
// imports here
#Service
#AllArgsConstructor
public class EventServiceImpl implements EventService {
private EventModelRepo eventModelRepo;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// methods that dont matter
public int createAPost(EventDetails eventDetails) {
//Some where here the isOwner(STRING) is called
}
public static void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
public boolean isOwner(String Owner) {
try {
getRequest("http://localhost:9024/login/isAuth?Username=" + Owner);
} catch (HttpResponseException e) {
System.out.println("Error: " + e.getContent());
return false;
} catch (IOException e) {
System.out.println("Could Not Connect To Site/Make Said Request. \nAre You In Testing? \nIf So This Is Ok.");
}
return true;
}
}
And here is my Junit:
//imports
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
// mocking the HTTP Call in isOwner()
HttpTransport transport = new MockHttpTransport();
HttpRequest request = null;
try {
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpResponse response = request.execute();
} catch (IOException e) {
e.printStackTrace();
}
EventDetails eventDetails = new EventDetails("username1", "resturant", "idk", "location.", ".com",
"no", "no p", "spring", "fair", "tes");
//If Owner Isn't Validate As Owner/Signed In
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
//doReturn(false).when(eventServiceImpl).isOwner(anyString());
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
So turns out one of the commentors on my post was correct. You can not mock a call from a #InjectMocks. But if you want to you need to have another annotation added to it. That annotation being #Spy. This annotation should be added in the test class, above the #InjectMocks.
More can be found here
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#Spy
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
I am trying to send a file to Remote SFTP server. I have created a factory and an outboundFlow for the same.
UploaderSftpConnectionFactoryBuilder
#Configuration
public class UploaderSftpConnectionFactoryBuilder {
#Value("${report-uploader.sftp-factory.host}")
private String host = null;
#Value("${report-uploader.sftp-factory.port}")
private Integer port = null;
#Value("classpath:${report-uploader.sftp-factory.privateKey}")
private Resource privateKey = null;
#Value("${report-uploader.sftp-factory.privateKeyPassphrase}")
private String privateKeyPassphrase = null;
#Value("${report-uploader.sftp-factory.maxConnections}")
private String maxConnections = null;
#Value("${report-uploader.sftp-factory.user}")
private String user = null;
#Value("${report-uploader.sftp-factory.poolSize}")
private Integer poolSize = null;
#Value("${report-uploader.sftp-factory.sessionWaitTimeout}")
private Long sessionWaitTimeout = null;
//#Bean(name = "cachedSftpSessionFactory")
public DefaultSftpSessionFactory getSftpSessionFactory() {
DefaultSftpSessionFactory defaultSftpSessionFactory = new DefaultSftpSessionFactory();
Optional.ofNullable(this.getHost()).ifPresent(value -> defaultSftpSessionFactory.setHost(value));
Optional.ofNullable(this.getPort()).ifPresent(value -> defaultSftpSessionFactory.setPort(port));
Optional.ofNullable(this.getPrivateKey()).ifPresent(
value -> defaultSftpSessionFactory.setPrivateKey(privateKey));
Optional.ofNullable(this.getPrivateKeyPassphrase()).ifPresent(
value -> defaultSftpSessionFactory.setPrivateKeyPassphrase(value));
Optional.ofNullable(this.getUser()).ifPresent(value -> defaultSftpSessionFactory.setUser(value));
return defaultSftpSessionFactory;
}
#Bean(name = "cachedSftpSessionFactory")
public CachingSessionFactory<LsEntry> getCachedSftpSessionFactory() {
CachingSessionFactory<LsEntry> cachedFtpSessionFactory = new CachingSessionFactory<LsEntry>(
getSftpSessionFactory());
cachedFtpSessionFactory.setPoolSize(poolSize);
cachedFtpSessionFactory.setSessionWaitTimeout(sessionWaitTimeout);
return cachedFtpSessionFactory;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Resource getPrivateKey() {
return privateKey;
}
public void setPrivateKey(Resource privateKey) {
this.privateKey = privateKey;
}
public String getPrivateKeyPassphrase() {
return privateKeyPassphrase;
}
public void setPrivateKeyPassphrase(String privateKeyPassphrase) {
this.privateKeyPassphrase = privateKeyPassphrase;
}
public String getMaxConnections() {
return maxConnections;
}
public void setMaxConnections(String maxConnections) {
this.maxConnections = maxConnections;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
Now i want to test the outbound flow using an integration test. For that i have created below testContext:
TestContextConfiguration
#Configuration
public class TestContextConfiguration {
#Configuration
#Import({ FakeSftpServer.class, JmxAutoConfiguration.class, IntegrationAutoConfiguration.class,
UploaderSftpConnectionFactoryBuilder.class })
#IntegrationComponentScan
public static class ContextConfiguration {
#Value("${report-uploader.reportingServer.fileEncoding}")
private String fileEncoding;
#Autowired
private FakeSftpServer fakeSftpServer;
#Autowired
#Qualifier("cachedSftpSessionFactory")
//CachingSessionFactory<LsEntry> cachedSftpSessionFactory;
DefaultSftpSessionFactory cachedSftpSessionFactory;
#Bean
public IntegrationFlow sftpOutboundFlow() {
return IntegrationFlows
.from("toSftpChannel")
.handle(Sftp.outboundAdapter(this.cachedSftpSessionFactory, FileExistsMode.REPLACE)
.charset(Charset.forName(fileEncoding)).remoteFileSeparator("\\")
.remoteDirectory(this.fakeSftpServer.getTargetSftpDirectory().getPath())
.fileNameExpression("payload.getName()").autoCreateDirectory(true)
.useTemporaryFileName(true).temporaryFileSuffix(".tranferring")
).get();
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
I have also created a fake sftp server as suggested # https://github.com/spring-projects/spring-integration-java-dsl/blob/master/src/test/java/org/springframework/integration/dsl/test/sftp/TestSftpServer.java
Below is my fake server:
FakeSftpServer
#Configuration("fakeSftpServer")
public class FakeSftpServer implements InitializingBean, DisposableBean {
private final SshServer server = SshServer.setUpDefaultServer();
private final int port = SocketUtils.findAvailableTcpPort();
private final TemporaryFolder sftpFolder;
private final TemporaryFolder localFolder;
private volatile File sftpRootFolder;
private volatile File sourceSftpDirectory;
private volatile File targetSftpDirectory;
private volatile File sourceLocalDirectory;
private volatile File targetLocalDirectory;
public FakeSftpServer() {
this.sftpFolder = new TemporaryFolder() {
#Override
public void create() throws IOException {
super.create();
sftpRootFolder = this.newFolder("sftpTest");
targetSftpDirectory = new File(sftpRootFolder, "sftpTarget");
targetSftpDirectory.mkdir();
}
};
this.localFolder = new TemporaryFolder() {
#Override
public void create() throws IOException {
super.create();
File rootFolder = this.newFolder("sftpTest");
sourceLocalDirectory = new File(rootFolder, "localSource");
sourceLocalDirectory.mkdirs();
File file = new File(sourceLocalDirectory, "localSource1.txt");
file.createNewFile();
file = new File(sourceLocalDirectory, "localSource2.txt");
file.createNewFile();
File subSourceLocalDirectory = new File(sourceLocalDirectory, "subLocalSource");
subSourceLocalDirectory.mkdir();
file = new File(subSourceLocalDirectory, "subLocalSource1.txt");
file.createNewFile();
}
};
}
#Override
public void afterPropertiesSet() throws Exception {
this.sftpFolder.create();
this.localFolder.create();
this.server.setPasswordAuthenticator((username, password, session) -> true);
this.server.setPort(this.port);
this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("src/test/resources/hostkey.ser")));
this.server.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
this.server.setFileSystemFactory(new VirtualFileSystemFactory(sftpRootFolder.toPath()));
this.server.start();
}
#Override
public void destroy() throws Exception {
this.server.stop();
this.sftpFolder.delete();
this.localFolder.delete();
}
public File getSourceLocalDirectory() {
return this.sourceLocalDirectory;
}
public File getTargetLocalDirectory() {
return this.targetLocalDirectory;
}
public String getTargetLocalDirectoryName() {
return this.targetLocalDirectory.getAbsolutePath() + File.separator;
}
public File getTargetSftpDirectory() {
return this.targetSftpDirectory;
}
public void recursiveDelete(File file) {
File[] files = file.listFiles();
if (files != null) {
for (File each : files) {
recursiveDelete(each);
}
}
if (!(file.equals(this.targetSftpDirectory) || file.equals(this.targetLocalDirectory))) {
file.delete();
}
}
}
Finally below is my test class
TestConnectionFactory
#ContextConfiguration(classes = { TestContextConfiguration.class }, initializers = {ConfigFileApplicationContextInitializer.class})
#RunWith(SpringJUnit4ClassRunner.class)
#DirtiesContext
public class TestConnectionFactory {
#Autowired
#Qualifier("cachedSftpSessionFactory")
CachingSessionFactory<LsEntry> cachedSftpSessionFactory;
//DefaultSftpSessionFactory cachedSftpSessionFactory;
#Autowired
FakeSftpServer fakeSftpServer;
#Autowired
#Qualifier("toSftpChannel")
private MessageChannel toSftpChannel;
#After
public void setupRemoteFileServers() {
this.fakeSftpServer.recursiveDelete(this.fakeSftpServer.getSourceLocalDirectory());
this.fakeSftpServer.recursiveDelete(this.fakeSftpServer.getTargetSftpDirectory());
}
#Test
public void testSftpOutboundFlow() {
boolean status = this.toSftpChannel.send(MessageBuilder.withPayload(new File(this.fakeSftpServer.getSourceLocalDirectory() + "\\" + "localSource1.txt")).build());
RemoteFileTemplate<ChannelSftp.LsEntry> template = new RemoteFileTemplate<>(this.cachedSftpSessionFactory);
ChannelSftp.LsEntry[] files = template.execute(session ->
session.list(this.fakeSftpServer.getTargetSftpDirectory() + "\\" + "localSource1.txt"));
assertEquals(1, files.length);
//assertEquals(3, files[0].getAttrs().getSize());
}
}
Now when i am running this test, I am getting the below exception:
org.springframework.messaging.MessagingException: ; nested exception is org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is java.lang.IllegalStateException: failed to create SFTP Session
at org.springframework.integration.dispatcher.AbstractDispatcher.wrapExceptionIfNecessary(AbstractDispatcher.java:133)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:120)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:101)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:97)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:286)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:245)
at com.sapient.lufthansa.reportuploader.config.TestConnectionFactory.testSftpOutboundFlow(TestConnectionFactory.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is java.lang.IllegalStateException: failed to create SFTP Session
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:345)
at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:211)
at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:201)
at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:193)
at org.springframework.integration.file.remote.handler.FileTransferringMessageHandler.handleMessageInternal(FileTransferringMessageHandler.java:110)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
... 36 more
Caused by: java.lang.IllegalStateException: failed to create SFTP Session
at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:355)
at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:49)
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:334)
... 42 more
Caused by: java.lang.IllegalStateException: failed to connect
at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:272)
at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:350)
... 44 more
Caused by: com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect
at com.jcraft.jsch.Util.createSocket(Util.java:349)
at com.jcraft.jsch.Session.connect(Session.java:215)
at com.jcraft.jsch.Session.connect(Session.java:183)
at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:263)
... 45 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.jcraft.jsch.Util.createSocket(Util.java:343)
... 48 more
which i am not able to resolve it and stuck on it for quite a time now. I am a beginner with spring-integration-dsl and any help woul be really appreciated.
Caused by: java.net.ConnectException: Connection refused: connect
You are connecting to the wrong port.
The test connection factory listens on a random port - you need to use the same port.
I am new to JUNIT testing but tried a lot to test the class UserProfileService. Please help or suggest possible errors I am doing:
#Path("/update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateProfile(final PartyProfile partyProfile) {
final ProxyResponse response = new ProxyResponse();
try {
final boolean isUpdated = partyProfileDao.updateProfile(partyProfile);
if (isUpdated) {
LOGGER.info("update Request completed successfully");
setSuccessResponse(response, "Request completed successfully");
try{
final String trailId = partyProfileDao.fetchPartyTrial(partyProfile.getPartyId());
activityPush(trailId, partyProfile.getPartyId());
}catch(Exception ex){
ex.printStackTrace();
LOGGER.error("Exception while triggering segmentation++");
}
} else {
LOGGER.info("Unable to update profile");
setErrorResponse(response, "PRFUPDT500", "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
} catch (Exception exc) {
LOGGER.error("Unable to update profile:" + exc.getMessage());
setInternalErrorResponse(exc, response, "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
return Response.ok(response).build();
}
I have written following JUNIT test:
public class PartyProfileServiceTest {
private PartyProfileDAO partyDAO;
private PartyProfileService partyService;
#Before
public void setUp() throws Exception {
partyDAO = EasyMock.createMock(PartyProfileDAO.class);
partyService = EasyMock.createMock(PartyProfileService.class);
partyService.setUserProfileDAO(partyDAO);
}
#Test
public void testUpdateValidProfile() throws Exception {
System.out.println("inside junit");
PartyProfile partyProfile = new PartyProfile();
partyProfile.setFirstName("adsfsdfg");
partyProfile.setAddress("adressabc");
partyProfile.setPartyId("dfdf");
partyProfile.getSalutation();
partyProfile.setMiddleName("asfsaf");
partyProfile.setLastName("easdsddff");
partyProfile.setNickName("srb");
partyProfile.setGender("m");
partyProfile.setUpdateDate("sdd");
partyProfile.setEducation("srg");
partyProfile.setInsurance("sg");
partyProfile.setState("sdfg");
partyProfile.setSiteId("fdg");
partyProfile.setRandomNo("feddg");
partyProfile.setPartyId("56666");
EasyMock.expect(partyDAO.updateProfile(partyProfile)).andReturn(true);
EasyMock.expect(partyDAO.fetchPartyTrial("validPartyId")).andReturn("pass");
EasyMock.replay(partyDAO);
EasyMock.expect(partyService.activityPush("pass", "validPartyId")).andReturn(true);
EasyMock.replay(partyService);
Response response = partyService.updateProfile(partyProfile);
ProxyResponse proxyResponse = (ProxyResponse) response.getEntity();
Assert.assertSame("Unable to update profile", proxyResponse.getData().get("message"));
}
}
Error:
java.lang.AssertionError:
Unexpected method call PartyProfileService.updateProfile(com.cts.vcoach.proxy.model.PartyProfile#11e170c):
PartyProfileService.setUserProfileDAO(EasyMock for class com.cts.vcoach.proxy.dao.PartyProfileDAO): expected: 1, actual: 0
PartyProfileService.activityPush("pass", "validPartyId"): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at com.cts.vcoach.proxy.service.rest.PartyProfileService$$EnhancerByCGLIB$$46a1112f.updateProfile(<generated>)
at com.cts.vcoach.proxy.service.rest.PartyProfileServiceTest.testUpdateValidProfile(PartyProfileServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
You're trying to test the class PartyProfileService. So you should create an instance of this class, and call its methods in your test. But that's not what you're doing. You're creating a mock instance of this class:
partyService = EasyMock.createMock(PartyProfileService.class);
Replace this line by
partyService = new PartyProfileService();
If you need to partially mock the service, i.e. mock the method activityPush(), but not the other ethods, then see the documentation for how to do that:
ToMock mock = createMockBuilder(ToMock.class)
.addMockedMethod("mockedMethod")
.createMock();