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));
}
}
Related
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 {
...
}
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);
}
}
For example I have some tests based on Set<Integer>. I want to run them with TreeSet and then with HashSet. Can I do it without manual initialization inside test method body?
Something like this:
public class SomeTest {
Set<Integer> set;
#Before
public void init() {
set = new HashSet<>();
}
// #Before
// public void init2() {
// set = new TreeSet<>();
// }
//test...
}
I want to run all tests with init() first and then with init2(). How can I do it?
A cleaner approach would be:
public abstract class SomeTestsForSets {
Set<Integer> set;
#Before
public abstract void init();
//test cases...
}
public class HashSetTests extends SomeTestsForSets {
#Override
public void init() {
this.set = new HashSet<>();
}
}
public class TreeSetTests extends SomeTestsForSets {
#Override
public void init() {
this.set = new TreeSet<>();
}
}
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{...}
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();
}