#MockClass is not working - java

I am new to jmockit and trying to execute the following online example.
The #MockClass is not working. My BookStore's getBookTitle() method is calling the function of orginal class instead of the mock class.
BookStore class:
public class BookStore {
public String getBookTitle(String isbn){
return BookStoreService.getBookTitle(isbn);
}
}
BookStoreService class:
public class BookStoreService {
public static String getBookTitle(String isbn){
return "Random";
}
}
Test class:
public class BookStoreTest {
private static Map<String, String> bookMap = new HashMap<String, String>(2);
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
}
#MockClass(realClass = BookStoreService.class)
public static class MockBookstoreService {
#Mock
public static String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
}
#Test
public void testGetBookTitle() throws Exception {
System.out.println("in testGetBookTitle()");
final String isbn = "0553293354";
final String expectedTitle = "Foundation";
BookStore store = new BookStore();
String title = store.getBookTitle(isbn);
System.out.println(title); // This prints "Random" instead of "Foundation"
Assert.assertEquals(title, expectedTitle);
}
}
PS: I am using TestNG

Using the latest stable version of jmockit you could do it like this:
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
new MockUp<BookStoreService>() {
#Mock
public String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
};
}
Remove the obsolete block:
public static class MockBookstoreService{...}

Related

How can I provide this sort of String builder class?

I like to have a Drive class where all files and folders for a project are managed.
My first attempt was pretty easy like a lot of functions (most of them with arguments).
Now I try to make it more fancy because it became more and more annoying to have a lot of functions, in which the desired one can be found. To not have an XY-problem here, I start with my dream.
I like to construct the Drive class in a way, so that it is super easy to find a certain file or folder.
If you look in the main function, I can find every needed file by writing a point and look which subclasses/methods are proposed to continue, till I find it and add .str to it. At every point, only the subclasses/methods will be proposed which makes sense at this point.
It almost works! It is more complicated to write and maintain as the first approach, but If I use it very often, it could be worth it.
I can:
go into subfolders
go into subfolders with name inside the argument
But there is an error if I define a fixed-name-subfolder of a fluid-name-folder like in the code below.
Now my questions:
how can I change the code so the main Function doesn't show this error?
would you recommend a completely different approach to the "make it easy to find strings inside a huge list of strings via making collections inside collections... of strings"-problem?
package utilities;
public class Drive_draft {
private static final String fs = System.getProperty("file.separator");
public static final String str = System.getProperty("user.home").concat(fs);
public static class IeCreation {
public static final String str = Drive_draft.str.concat(".meetings").concat(fs);
public static class Abstract {
public static final String str = IeCreation.str.concat("Abstracts").concat(fs);
}
public static class Meeting {
public static final String str = IeCreation.str.concat("Ueberordnungen").concat(fs);
}
}
public static class MetsSIPs {
public static final String str = Drive_draft.str.concat("workspace").concat(fs).concat("metsSIPs").concat(fs);
public static class preSIPs {
public static final String str = MetsSIPs.str.concat("preSIPs").concat(fs);
}
public static class RosettaInstance {
private static class MaterialflowId {
public static String str;
private static class ProducerId {
public static String str;
private static class Abstract {
public static String str;
public static class Mets {
public static final String str = Abstract.str.concat("content").concat(fs).concat("ie1.xml");
}
}
private static class Meeting {
public static String str;
}
public static Abstract Abstract (String value) {
Abstract ret = new Abstract();
ProducerId.Abstract.str = str.concat(value).concat(fs);
return ret;
}
public static Meeting Meeting (String value) {
Meeting ret = new Meeting();
ProducerId.Meeting.str = str.concat(value).concat(fs);
return ret;
}
}
public static ProducerId ProducerId (String value) {
ProducerId ret = new ProducerId();
MaterialflowId.ProducerId.str = str.concat(value).concat(fs);
return ret;
}
}
public static MaterialflowId MaterialflowId (String value) {
MaterialflowId ret = new MaterialflowId();
MaterialflowId.str = str.concat(value).concat(fs);
return ret;
}
}
public static class Dev extends RosettaInstance {
public static final String str = MetsSIPs.str.concat("dev").concat(fs);
}
public static class Test extends RosettaInstance {
public static final String str = MetsSIPs.str.concat("test").concat(fs);
}
public static class Prod extends RosettaInstance{
public static final String str = MetsSIPs.str.concat("prod").concat(fs);
}
}
#SuppressWarnings("static-access")
public static void main(String[] args) {
System.out.println(Drive_draft.MetsSIPs.Dev.str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("2").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").Abstract("est").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").Meeting("oast").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").Abstract("est").Mets.str); //Error: Mets cannot be resolved or is not a field
}
}
You can encode your "directory" structure with interfaces, with each interface declaring what the user can do next. Then the implementation can use a StringBuilder to just append the appropriate snippets and keep returning this.
// PathBuilderInterfaces.java
public class PathBuilderInterfaces {
public interface Buildable {
String build();
}
public interface Drive extends Buildable {
IeCreation ieCreation();
MetsSIPs metsSIPs();
}
public interface IeCreation extends Buildable {
String ieCreationAbstract();
String meeting();
}
public interface MetsSIPs extends Buildable {
RosettaInstance dev();
RosettaInstance test();
RosettaInstance prod();
}
public interface RosettaInstance extends Buildable {
MaterialFlowId materialFlowId(String value);
}
public interface MaterialFlowId extends Buildable {
ProducerId producerId(String value);
}
public interface ProducerId extends Buildable {
Abstract producerIdAbstract(String value);
String meeting(String value);
}
public interface Abstract extends Buildable {
String mets();
}
}
// PathBuilder.java
import static com.example.somepackage.PathBuilderInterfaces.*;
public class PathBuilder implements Drive, IeCreation, MetsSIPs, RosettaInstance, MaterialFlowId, ProducerId, Abstract{
private StringBuilder builder = new StringBuilder(str);
private static final String fs = System.getProperty("file.separator");
public static final String str = System.getProperty("user.home").concat(fs);
public static Drive drive() {
return new PathBuilder();
}
#Override
public String build() {
return builder.toString();
}
#Override
public IeCreation ieCreation() {
builder.append(".meetings").append(fs);
return this;
}
#Override
public MetsSIPs metsSIPs() {
builder.append("workspace").append(fs).append("metsSIPs").append(fs);
return this;
}
#Override
public RosettaInstance dev() {
builder.append("dev").append(fs);
return this;
}
#Override
public RosettaInstance test() {
builder.append("test").append(fs);
return this;
}
#Override
public RosettaInstance prod() {
builder.append("prod").append(fs);
return this;
}
#Override
public MaterialFlowId materialFlowId(String value) {
builder.append(value).append(fs);
return this;
}
#Override
public ProducerId producerId(String value) {
builder.append(value).append(fs);
return this;
}
#Override
public Abstract producerIdAbstract(String value) {
builder.append(value).append(fs);
return this;
}
#Override
public String meeting(String value) {
builder.append(value).append(fs);
return build();
}
#Override
public String mets() {
builder.append("content").append(fs).append("ie1.xml");
return build();
}
#Override
public String ieCreationAbstract() {
builder.append("Abstracts").append(fs);
return build();
}
#Override
public String meeting() {
builder.append("Ueberordnungen").append(fs);
return build();
}
}
Usage:
// in a main method somewhere
System.out.println(
PathBuilder.drive()
.metsSIPs()
.dev()
.materialFlowId("1")
.producerId("t")
.producerIdAbstract("est")
.mets());

Unit test with JUnit 5

Hi all i receive Nullpointer when trying to execute this unit test.I want to test e class which receive 3 parameters and returns a string. I think i need to make #Before or something else but it didn't works. Do you have suggestions...Thanks !
public class UrlConstructorTest {
private UrlConstructor urlConstructor;
#Before
public void setUp() {
urlConstructor = new UrlConstructor();
}
public static final String TEST_UPDATE_MANIFEST_SR = "/packages/proxyId/test/test1/123/test3/test_test";
#Test
public void constructUpdateManifestSrInSasTokenTest() {
String result = urlConstructor.composeDeviceRegistrationUrl("test","test123","test");
System.out.println(result);
assertNotNull(result);
assertEquals(TEST, result);
}
}
UrlConstructor is define like this:
#Component
public class UrlConstructor {
And this is the method in this class:
public String composeDUrl(String deviceId, String scopeId) {
return String.format(Constants.socpe, tes, test);
}
In Junit5, you should be using #BeforeEach. Or you can get rid of that setUp method completely.
public class UrlConstructorTest {
private final UrlConstructor urlConstructor = new UrlConstructor();
public static final String TEST_SR = "/packages/proxyId/testID/product/testscope/testcomponent/coomponent_up";
#Test
public void constructTest() {
String result = urlConstructor.composeDeviceRegistrationUrl("testID","coomponent_up","testscope");
System.out.println(result);
assertNotNull(result);
assertEquals(TEST_SR, result);
}
}

Why the Instance<Object> is null?

I have the following structure:
public class StringFactory {
#Inject
private Instance<StringFormatter> formatterInstances;
#PostConstruct
public void init() {
for (AddressFormatter formatter : formatterInstances) {
System.out.println("String formater: " + formatter);
}
}
}
StringFormatter
interface StringFormatter {
String createFormattedString(final String x);
}
StringFormaterForKR
public class StringFormaterForKR implements StringFormatter {
#Override
public String createFormattedString(String x) {
return null;
}
DefaultStringFormater
public class DefaultStringFormater implements StringFormatter {
#Override
public String createFormattedString(String x) {
return null;
}
Test
public class Test() {
public static void main(String args[]) {
StringFactory factory = new StringFactory();
}
}
I don't understand why formatterInstances is null ?
And I saw that the message from PostConstruct is never printed...
Do you have any explication for this ?

JMockit `Mockup` class returns null for own new instances from within itself [duplicate]

I have a static method which will be invoking from test method in a class as bellow
public class MyClass
{
private static boolean mockMethod( String input )
{
boolean value;
//do something to value
return value;
}
public static boolean methodToTest()
{
boolean getVal = mockMethod( "input" );
//do something to getVal
return getVal;
}
}
I want to write a test case for method methodToTest by mocking mockMethod.
Tried as bellow and it doesn't give any output
#Before
public void init()
{
Mockit.setUpMock( MyClass.class, MyClassMocked.class );
}
public static class MyClassMocked extends MockUp<MyClass>
{
#Mock
private static boolean mockMethod( String input )
{
return true;
}
}
#Test
public void testMethodToTest()
{
assertTrue( ( MyClass.methodToTest() );
}
To mock your static method:
new MockUp<MyClass>()
{
#Mock
boolean mockMethod( String input ) // no access modifier required
{
return true;
}
};
To mock the static private method:
#Mocked({"mockMethod"})
MyClass myClass;
String result;
#Before
public void init()
{
new Expectations(myClass)
{
{
invoke(MyClass.class, "mockMethod", anyString);
returns(result);
}
}
}
#Test
public void testMethodToTest()
{
result = "true"; // Replace result with what you want to test...
assertTrue( ( MyClass.methodToTest() );
}
From JavaDoc:
Object mockit.Invocations.invoke(Class methodOwner, String methodName, Object... methodArgs)
Specifies an expected invocation to a given static method, with a given list of arguments.
There is another way of mocking static methods using JMockit (using Delegate class). I find it more convenient and elegant.
public class Service {
public String addSuffix(String str) { // method to be tested
return Utils.staticMethod(str);
}
}
public class Utils {
public static String staticMethod(String s) { // method to be mocked
String suffix = DatabaseManager.findSuffix("default_suffix");
return s.concat(suffix);
}
}
public class Test {
#Tested
Service service;
#Mocked
Utils utils; // #Mocked will make sure all methods will be mocked (including static methods)
#Test
public void test() {
new Expectations {{
Utils.staticMethod(anyString); times = 1; result = new Delegate() {
public static String staticMethod(String s) { // should have the same signature (method name and parameters) as Utils#staticMethod
return ""; // provide custom implementation for your Utils#staticMethod
}
}
}}
service.addSuffix("test_value");
new Verifications {{
String s;
Utils.staticMethod(s = withCapture()); times = 1;
assertEquals("test_value", s); // assert that Service#addSuffix propagated "test_value" to Utils#staticMethod
}}
}
}
Reference:
https://jmockit.github.io/tutorial/Mocking.html#delegates
https://jmockit.github.io/tutorial/Mocking.html#withCapture

How to mock a static method from JMockit

I have a static method which will be invoking from test method in a class as bellow
public class MyClass
{
private static boolean mockMethod( String input )
{
boolean value;
//do something to value
return value;
}
public static boolean methodToTest()
{
boolean getVal = mockMethod( "input" );
//do something to getVal
return getVal;
}
}
I want to write a test case for method methodToTest by mocking mockMethod.
Tried as bellow and it doesn't give any output
#Before
public void init()
{
Mockit.setUpMock( MyClass.class, MyClassMocked.class );
}
public static class MyClassMocked extends MockUp<MyClass>
{
#Mock
private static boolean mockMethod( String input )
{
return true;
}
}
#Test
public void testMethodToTest()
{
assertTrue( ( MyClass.methodToTest() );
}
To mock your static method:
new MockUp<MyClass>()
{
#Mock
boolean mockMethod( String input ) // no access modifier required
{
return true;
}
};
To mock the static private method:
#Mocked({"mockMethod"})
MyClass myClass;
String result;
#Before
public void init()
{
new Expectations(myClass)
{
{
invoke(MyClass.class, "mockMethod", anyString);
returns(result);
}
}
}
#Test
public void testMethodToTest()
{
result = "true"; // Replace result with what you want to test...
assertTrue( ( MyClass.methodToTest() );
}
From JavaDoc:
Object mockit.Invocations.invoke(Class methodOwner, String methodName, Object... methodArgs)
Specifies an expected invocation to a given static method, with a given list of arguments.
There is another way of mocking static methods using JMockit (using Delegate class). I find it more convenient and elegant.
public class Service {
public String addSuffix(String str) { // method to be tested
return Utils.staticMethod(str);
}
}
public class Utils {
public static String staticMethod(String s) { // method to be mocked
String suffix = DatabaseManager.findSuffix("default_suffix");
return s.concat(suffix);
}
}
public class Test {
#Tested
Service service;
#Mocked
Utils utils; // #Mocked will make sure all methods will be mocked (including static methods)
#Test
public void test() {
new Expectations {{
Utils.staticMethod(anyString); times = 1; result = new Delegate() {
public static String staticMethod(String s) { // should have the same signature (method name and parameters) as Utils#staticMethod
return ""; // provide custom implementation for your Utils#staticMethod
}
}
}}
service.addSuffix("test_value");
new Verifications {{
String s;
Utils.staticMethod(s = withCapture()); times = 1;
assertEquals("test_value", s); // assert that Service#addSuffix propagated "test_value" to Utils#staticMethod
}}
}
}
Reference:
https://jmockit.github.io/tutorial/Mocking.html#delegates
https://jmockit.github.io/tutorial/Mocking.html#withCapture

Categories