Unable to mock a private method via jmockit - java

Please help, this mock isn't working :
class ClassBeingTested {
private AnotherClass anotherClass;
public void someMethod() {
int ans = anotherClass.targetMethod(5);
// Use ans here
}
}
// My test
ClassBeingTested classObject;
AnotherClass anotherClassObject;
#Before
public void setup() {
// Initialize anotherClassObject here
classObject = new ClassBeingTested(anotherClassObject);
new NonStrictExpectations(anotherClassObject) {{
invoke(anotherClassObject, "targetMethod", Integer.class); result = 100;
}};
}
#Test
public void testSomeMethod() {
classObject.someMethod();
}

Mocking worked as soon as I replaced Integer.class with actual expected int value.
new NonStrictExpectations(anotherClassObject) {{
invoke(anotherClassObject, "targetMethod", 5); result = 100;
}};

How about this way of mocking with JMockit?
import mockit.Injectable;
import mockit.Tested;
...
#Tested
ClassBeingTested classObject;
#Injectable
AnotherClass anotherClassObject;
#Before
public void setup() {
new Expectations() {{
anotherClassObject.targetMethod(anyInt); result = 100;
}};
}
#Test
public void testSomeMethod() {
classObject.someMethod();
}

Related

Java: How to Mock a protected method inside a static child class

I am having a protected method inside a static child class. I am running a testcase , its getting successful but code coverage is not increasing.
public class A{
private static final String var1 = "key1";
protected static class B extends OsCmd{
private String abc1;
private String abc2;
protected B(String xyz, String xyz2) {
this.abc1 = xyz;
this.abc2 = xyz2;
}
#Override
protected void updateEnv(Map<String, String> env) {
env.put(VAR1, "FALSE");
env.put(VAR2, "TRUE");
env.put("key3", abc1);
env.put("key4", abc2);
}
}
}
Below is my test case
#ExtendWith(MockitoExtension.class)
public class ATest {
private A mockA;
#BeforeEach
public void setup() {
mockA = Mockito.spy(A.class);
}
#Test
public void test2() {
try (MockedConstruction mockedConstruction =
mockConstruction(A.B.class)) {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
A.B mockB =
new A.B("a", "b");
//doNothing().when(mockB).updateEnv(map);
mockB.updateEnv(map);
}
}
}
Can someone please help here, what mistake i am doing?
When you mock the constructor, then all internal method calls are also mocked and do not go through the actual code.
If you remove the following try-with-resources:
try (MockedConstruction mockedConstruction =
mockConstruction(A.B.class))
The real code will be executed and the coverage will increase.

Testing for class field with is share among methods

I have a Java class as follow
public class MyClass {
private final ShowFactory showFactory;
private SomeShow someShow;
public MyClass(ShowFactory showFactory) {
this.showFactory = showFactory;
startShow();
}
public void startShow() {
someShow = showFactory.createShow();
someShow.start();
}
public void showSomething() {
MagicBox magicBox = new MagicBox();
someShow.showSomething(magicBox);
}
public void stopShow() {
someShow.stop();
}
}
and trying to test showSomething method. Complete test file is as follow
public class MyClassTest {
private ShowFactory showFactory;
private SomeShow someShow;
#Before
public void setUp() {
showFactory = mock(ShowFactory.class);
someShow = mock(SomeShow.class);
when(showFactory.createShow()).thenReturn(someShow);
}
#Test
public void shouldStartShow() {
new MyClass(showFactory);
verify(someShow).start();
}
#Test
public void shouldShowSomething() throws Exception {
MagicBox magicBox = mock(MagicBox.class);
PowerMockito.whenNew(MagicBox.class).withAnyArguments().thenReturn(magicBox);
doNothing().when(someShow).showSomething(magicBox);
InOrder inOrder = inOrder(someShow);
MyClass myClass = new MyClass(showFactory);
myClass.showSomething();
inOrder.verify(someShow).start();
inOrder.verify(someShow).showSomething(magicBox);
}
#Test
public void shouldStopShow() {
MyClass myClass = new MyClass(showFactory);
myClass.stopShow();
verify(someShow).start();
verify(someShow).stop();
}
}
But test shouldShowSomething is failing with error Wanted but not invoked. Any thing I am missing here? Any suggestion?
It was simple fix. After reading through https://github.com/powermock/powermock/wiki/MockConstructor#quick-summary (thanks to #roby) turns out I was missing the #PrepareForTest annotation for the class.
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class MyClassTest {
...
}

calling objects from other methods in java

I am a novice programmer and was wondering how I can create a test method that calls the object from the setUp() method above. Is there a better way to do this where a method is used to initialize the objects and the test method does the testing??
Any tips are appreciated..
public class ProjectTeamRemoveMemberTest {
//Initialize test object
public static void setUp() {
Date date = new Date();
Employee e = new Employee("Alice", date);
Project p = new Project();
}
#Test
public void removeTeamMember_True_ifMemberIsSelected() {
setUp();
assertEquals(true, p.removeTeamMember(e));
}
}
You can create those variables on class level, assign values in setup and refere to them in a test.
public class ProjectTeamRemoveMemberTest {
static Date date;
static Employee e;
static Project p;
//Initialize test object
public static void setUp() {
date = new Date();
e = new Employee("Alice", date);
p = new Project();
}
#Test
public void removeTeamMember_True_ifMemberIsSelected() {
assertEquals(true, p.removeTeamMember(e));
}
}
You can use #Before annotation or #BeforeEach (if you use JUnit5)
public class ProjectTeamRemoveMemberTest {
private Employee e;
private Project p;
#Before // will be called before each test mehod
public void createEmployee() {
e = new Employee("Alice", new Date());
}
#Before
public void createProject() {
p = new Project();
}
#Test
public void removeTeamMember_True_ifMemberIsSelected() {
assertEquals(true, p.removeTeamMember(e));
}
}

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

Define expectations for public final instance variable

I'm new at unit testing and am running into an issue with jMock that I can't seem to figure out. I have a public final instance variable which I need to define an expectation for, but I can't get it to work. If I make a getter for the variable, it works, but I'd rather not have to create a bunch of getters just to make unit testing work. Any help on how to do this would be much appreciated. Here's some code illustraiting what I'm trying to do:
public class Main {
private SimpleObject simpleObject;
public Main(SimpleObject o){
this.simpleObject = o;
}
public int iDontWork(){
return simpleObject.myList.size();
}
public int iWork(){
return simpleObject.getMyList().size();
}
}
My test:
#RunWith(JMock.class)
public class MainTest {
Mockery context = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
#Mock
SimpleObject simpleObject;
private Main main;
#Before
public void setup(){
main = new Main(simpleObject);
}
#Test
public void itWorks() {
context.checking(new Expectations() {{
oneOf(simpleObject).getMyList();
will(returnValue(new ArrayList<String>(Arrays.asList("Hey"))));
}});
int i = main.iWork();
assertEquals(1, i);
}
#Test
public void itDoesntWork() {
context.checking(new Expectations() {{
oneOf(simpleObject).myList.size(); will(returnValue(1));
}});
int i = main.iDontWork();
assertEquals(1, i);
}
}
SimpleObject:
public class SimpleObject {
public final List<String> myList;
public SimpleObject(){
myList = Collections.unmodifiableList(Arrays.asList("Hey"));
}
public List<String> getMyList(){
return myList;
}
}
A mock object implements methods of the real object. It does not have fields of the real object (even if these fields are public).

Categories