How to use the mock object of the test class and call main method from the test class - mockito

In the test class trying to test the main method and not sure how to use the mock object here.
How to use the mock object orders to call the main method and it's methods inside the main method
Any suggestions on how this can be done?
public class Orders {
public static void main(String[] s) {
Orders jp = new Orders();
jp.method1();
List<OrderItems> lstOrdItms = jp.getListOrderItems();
jp.processOrderItems( lstOrdItms );
}
public void method1(List<OrderItem> lstOrderItem) {
.........
}
public List<OrderItem> getListOrderItems() {
............
}
public void processOrderItems() {
............
}
}
public class OrdersTest {
#Mocks
Orders orders;
.....
#Before
public void setUp() {
........
}
#Test
public void testMain() throws SQLException {
// Not sure how to test here
// This will actually execute the main method instead of mock.
orders.main(new String[]{});
}
}

Related

Stub all the method call including a method call inside it, from another class using mockito

How to stub a System.currentTimeMillis() in the classB from classA?
Class A:
public classA {
#Test public void timeTest() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(10L);
B.testPowerMock(); }
}
Class B:
public class B {
public static void testPowerMock() {
System.out.println(System.currentTimeMillis());
}
}

Mockito/PowerMockito: mock final static member cannot return different values in different methods

There is a final static member in class ToBeTestClass:
protected final static LMSServiceHelper externalService;
I mock it with
#Mock
protected LMSServiceHelper externalService;
Then I want to get different values in different test methods:
public void testMethod1() {
PowerMockito.when(externalService.getSomething).thenReturn("aaa");
}
public void testMethod2() {
PowerMockito.when(externalService.getSomething).thenReturn("bbb");
}
public void testMethod3() {
PowerMockito.when(externalService.getSomething).thenReturn("ccc");
}
However, I can't get "bbb" or "ccc" whereas always get "aaa". It seems when I set the return value first time, and it will never changes.
Anyone has met this?
#Before
public void setUp() {
Mockito.when(externalService.getSomething)
.thenReturn("aaa")
.thenReturn("ccc")
.thenReturn("ccc"); //any subsequent call will return "ccc"
}
How to tell a Mockito mock object to return something different the next time it is called?
Reset your mocked object as shown below then you will see different values
public void testMethod1() {
PowerMockito.when(externalService.getSomething).thenReturn("aaa");
Mockito.reset(externalService);
}
public void testMethod2() {
PowerMockito.when(externalService.getSomething).thenReturn("bbb");
Mockito.reset(externalService);
}
public void testMethod3() {
PowerMockito.when(externalService.getSomething).thenReturn("ccc");
Mockito.reset(externalService);
}

Mocking a method inside my test class

Android Studio 2.3
I have the following method I want to test inside my model class:
public class RecipeListModelImp implements RecipeListModelContract {
private Subscription subscription;
private RecipesAPI recipesAPI;
private RecipeSchedulers recipeSchedulers;
#Inject
public RecipeListModelImp(#NonNull RecipesAPI recipesAPI, #NonNull RecipeSchedulers recipeSchedulers) {
this.recipesAPI = Preconditions.checkNotNull(recipesAPI);
this.recipeSchedulers = Preconditions.checkNotNull(recipeSchedulers);
}
#Override
public void getRecipesFromAPI(final RecipeGetAllListener recipeGetAllListener) {
subscription = recipesAPI.getAllRecipes()
.subscribeOn(recipeSchedulers.getBackgroundScheduler())
.observeOn(recipeSchedulers.getUIScheduler())
.subscribe(new Subscriber<List<Recipe>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
recipeGetAllListener.onRecipeGetAllFailure(e.getMessage());
}
#Override
public void onNext(List<Recipe> recipe) {
recipeGetAllListener.onRecipeGetAllSuccess(recipe);
}
});
}
#Override
public void shutdown() {
if(subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
Inside my test class I am testing like this:
public class RecipeListModelImpTest {
#Mock Subscription subscription;
#Mock RecipesAPI recipesAPI;
#Mock RecipeListModelContract.RecipeGetAllListener recipeGetAllListener;
#Mock List<Recipe> recipes;
#Inject RecipeSchedulers recipeSchedulers;
private RecipeListModelContract recipeListModel;
#Before
public void setup() {
TestBusbyComponent testBusbyComponent = DaggerTestBusbyComponent.builder()
.mockRecipeSchedulersModule(new MockRecipeSchedulersModule())
.build();
testBusbyComponent.inject(RecipeListModelImpTest.this);
MockitoAnnotations.initMocks(RecipeListModelImpTest.this);
recipeListModel = new RecipeListModelImp(recipesAPI, recipeSchedulers);
}
#Test(expected = NullPointerException.class)
public void testShouldThrowExceptionOnNullParameter() {
recipeListModel = new RecipeListModelImp(null, null);
}
#Test
public void testRecipeListModelShouldNotBeNull() {
assertNotNull(recipeListModel);
}
#Test
public void testShouldGetRecipesFromAPI() {
when(recipesAPI.getAllRecipes()).thenReturn(Observable.just(recipes));
recipeListModel.getRecipesFromAPI(recipeGetAllListener);
verify(recipesAPI, times(1)).getAllRecipes();
verify(recipeGetAllListener, times(1)).onRecipeGetAllSuccess(recipes);
verify(recipeGetAllListener, never()).onRecipeGetAllFailure(anyString());
}
#Test
public void testShouldFailToGetRecipesFromAPI() {
when(recipesAPI.getAllRecipes())
.thenReturn(Observable.<List<Recipe>>error(
new Throwable(new RuntimeException("Failed to get recipes"))));
recipeListModel.getRecipesFromAPI(recipeGetAllListener);
verify(recipesAPI, times(1)).getAllRecipes();
verify(recipeGetAllListener, times(1)).onRecipeGetAllFailure(anyString());
verify(recipeGetAllListener, never()).onRecipeGetAllSuccess(recipes);
}
#Test
public void testShouldShutdown() {
when(subscription.isUnsubscribed()).thenReturn(false);
final Field subscriptionField;
try {
subscriptionField = recipeListModel.getClass().getDeclaredField("subscription");
subscriptionField.setAccessible(true);
subscriptionField.set(recipeListModel, subscription);
} catch(NoSuchFieldException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
recipeListModel.shutdown();
verify(subscription, times(1)).unsubscribe();
}
}
However, the problem is the Subscription in my model class is always null so will never enter the if blook. Is there any way to test this with using Mockito or spys?
Many thanks for any suggestions,
You should for testing recipeListModel class, where you have shutdown() method , set mock into this class.
If you don't have set method for subscription in recipeListModel , or constructor param.... ),you can set mock object with reflection like :
#Test
public void testShouldShutdown() {
Subscription subscription = mock(Subscription.class);
when(subscription.isUnsubscribed()).thenReturn(false);
Field subscriptionField = recipeListModel.getClass().getDeclaredField("subscription");
subscriptionField.setAccessible(true);
subscriptionField.set(recipeListModel, subscriptionMock);
recipeListModel.shutdown();
verify(subscription, times(1)).unsubscribe();
}
after your update :
if you can't change way of creation , you should mock it like (full way of creation) , i don't know your api , so it's just idea:
Subscription subscription = mock(Subscription.class);
when(subscription.isUnsubscribed()).thenReturn(false);
// preparation mock for create Subscription
//for recipesAPI.getAllRecipes()
Object mockFor_getAllRecipes = mock(....);
when(recipesAPI.getAllRecipes()).thenReturn(mockFor_getAllRecipes );
//for subscribeOn(recipeSchedulers.getBackgroundScheduler())
Object mockFor_subscribeOn = mock();
when(mockFor_getAllRecipes.subscribeOn(any())).thenReturn(mockFor_subscribeOn);
//for .observeOn(recipeSchedulers.getUIScheduler())
Object mockFor_observeOn = mock();
when(mockFor_subscribeOn .observeOn(any())).thenReturn(observeOn);
// for .subscribe
when(observeOn.subscribe(any()).thenReturn(subscription);

in BeforeClass method how to insert init data to db

I have a UserServiceTest, I want to init load some user data to database for tests e.g. queryByName, groupByAge and so on . And I want to only load once in this class, so I want to use BeforeClass
#BeforeClass
public static void init(){
// ...
}
but in this case I find I cannot use jdbcTemplate to insert data just like in Before e.g.
#Before
public void setUp(){
// prepare test data first
jdbcTemplate.execute("insert into user(firstname,lastname,birthday) values(...);");
}
So in BeforeClass method how to insert init data?
Alternatively you can use TestExecutionListeners in order to initialise your database before test class.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestConfig.class)
#TestExecutionListeners(mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS, listeners = {
DbInitializerTestListener.class })
public class DbTest {
}
public class DbInitializerTestListener extends AbstractTestExecutionListener {
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public void beforeTestClass(TestContext testContext) throws Exception {
testContext.getApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this);
jdbcTemplate.execute("insert into user(firstname,lastname,birthday) values(...);");
}
}
Or you may consider DbUnit framework.

Groovy Inner Classes wont work with Apache Wicket

Im trying to write simple things with Apache Wicket (6.15.0) and Groovy (2.2.2 or 2.3.1). And Im having trouble with inner classes.
class CreatePaymentPanel extends Panel {
public CreatePaymentPanel(String id) {
super(id)
add(new PaymentSelectFragment('currentPanel').setOutputMarkupId(true))
}
public class PaymentSelectFragment extends Fragment {
public PaymentSelectFragment(String id) {
super(id, 'selectFragment', CreatePaymentPanel.this) // problem here
add(new AjaxLink('cardButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
})
add(new AjaxLink('terminalButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
});
}
} // end of PaymentSelectFragment class
} // end of CreatePaymentPanel class
Groovy tries to find a property "this" in CreatePaymentPanel class.. How to workaround this? It is a valid java code, but not groovy.
However,
Test.groovy:
class Test {
static void main(String[] args) {
def a = new A()
}
static class A {
A() {
def c = new C()
}
public void sayA() { println 'saying A' }
class B {
public B(A instance) {
A.this.sayA()
instance.sayA()
}
}
/**
* The problem occurs here
*/
class C extends B {
public C() {
super(A.this) // groovy tries to find property "this" in A class
sayA()
}
}
}
}
Above code wont work, the same error occurs, like in Wicket's case.
And TestJava.java, the same and working:
public class TestJava {
public static void main(String[] args) {
A a = new A();
}
static class A {
A() {
C c = new C();
}
public void sayA() {
System.out.println("saying A");
}
class B {
public B(A instance) {
instance.sayA();
}
}
/**
* This works fine
*/
class C extends B {
public C() {
super(A.this);
sayA();
}
}
}
}
What I am missing?
You can't refer to a CreatePaymentPanel.this inside of PaymentSelectFragment because there is no instance of CreatePamentPanel that would be accessible there. What would you expect that to evaluate to if it were allowed?

Resources