Duplicate application of the same mockup class - jmockit

When does the below error
java.lang.IllegalStateException: Duplicate application of the same
mock-up class_ exception
occurs?
#Before
public void setUp() throws Exception {
new MockUp<URL>() {
#Mock
public void $init(String location) {}
}.getMockInstance();
new MockUp<CommunicationUtils>() {
#Mock
public void $clinit() {}
}.getMockInstance();
}
At line number 7, I am getting this exception.

Related

When attaching agent to running process, bytebuddy transformer doesn't seem to take effect

The code of my program to be attached is as below.
public class Foo {
}
public class TestEntry {
public TestEntry() {
}
public static void main(String[] args) throws Exception {
try
{
while(true)
{
System.out.println(new Foo().toString());
Thread.sleep(1000);
}
}
catch(Exception e)
{}
}
}
What I attempt to do is to make Foo.toString() returns 'test' by using the following agent.
public class InjectionAgent {
public InjectionAgent() {
}
public static void agentmain(String args, Instrumentation inst) throws Exception
{
System.out.println("agentmain Args:" + args);
new AgentBuilder.Default()
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("test"));
}
}).installOn(inst);
}
public static void premain(String args, Instrumentation inst) throws Exception
{
System.out.println("premain Args:" + args);
new AgentBuilder.Default()
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("test"));
}
}).installOn(inst);
}
}
I notice that, it was successful when I using -javaagent way, whereas attach way failed, here is code for attach.
public class Injection {
public Injection() {
}
public static void main(String[] args) throws AttachNotSupportedException, IOException, AgentLoadException, AgentInitializationException, InterruptedException {
VirtualMachine vm = null;
String agentjarpath = args[0];
vm = VirtualMachine.attach(args[1]);
vm.loadAgent(agentjarpath, "This is Args to the Agent.");
vm.detach();
}
}
I tried to add AgentBuilder.Listener.StreamWriting.toSystemOut() to the agent, after attaching, the output of TestEntry shows
[Byte Buddy] DISCOVERY Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
[Byte Buddy] TRANSFORM Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
[Byte Buddy] COMPLETE Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
Foo#7f31245a
Foo#6d6f6e28
Foo#135fbaa4
Foo#45ee12a7
Foo#330bedb4
==================================Update=====================================
I defined a public method 'Bar' in Foo like this
public class Foo {
public String Bar()
{
return "Bar";
}
}
and then I was trying to make Foo.Bar() returns "modified" in the following way:
public static void agentmain(String args, Instrumentation inst) throws Exception
{
System.out.println("agentmain Args:" + args);
premain(args, inst);
new AgentBuilder.Default()
.with(RedefinitionStrategy.RETRANSFORMATION)
.disableClassFormatChanges()
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.visit(Advice.to(InjectionTemplate.class).on(ElementMatchers.named("Bar")));
}
})
.installOn(inst);
}
static class InjectionTemplate {
#Advice.OnMethodExit
static void exit(#Advice.Return String self) {
System.out.println(self.toString() + " " + self.getClass().toString());
self = new String("modified");
}
}
but I got this error:
java.lang.IllegalStateException: Cannot write to read-only parameter class java.lang.String at 1
any suggestions?
It does not seem like you are using redefinition for your agent. You can activate it using:
new AgentBuilder.Default()
.with(RedefinitionStrategy.RETRANSFORMATION)
.disableClassFormatChanges();
The last part is required on most JVMs (with the notable exception of the dynamic code evolution VM, a custom build of HotSpot). It tells Byte Buddy to not add fields or methods, what most VMs do not support.
In this case, it is no longer possible to invoke the original implementation of a method what is however not required for your FixedValue. Typically, users of Byte Buddy take advantage of Advice when creating an agent that applies dynamic transformations of classes.

AutoMapper IMappingEngine ConfigurationStore Initialize Not Happening

AutoMapper Version Used : 3.3.10
[TestClass]
public class AppControllerTests
{
private IMappingEngine _mappingEngine = null;
private ConfigurationStore _configurationStore = null;
[TestInitialize]
public void SetUp()
{
_configurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
_configurationStore.AddProfile(new AutoMapperProfile.AppProfile());
_mappingEngine = new MappingEngine(_configurationStore);
}
[TestMethod]
public void GetAppByAccountID()
{
// Error line
var mappingResult = _mappingEngine.Map<Category>(categoryList).AsQueryable();
}
}
public class AppProfile : Profile
{
protected override void Configure()
{
AutoMapperMappingConfigurations();
}
public void AutoMapperMappingConfigurations()
{
Mapper.CreateMap<DomainModels.Category, Category>().ReverseMap();
}
}
Exception:
An exception of type 'AutoMapper.AutoMapperMappingException'
occurred in AutoMapper.dll but was not handled in user code.
Suspect the
_configurationStore.AddProfile(new OOS.PresentationModelService.AutoMapperProfile.AppProfile());
is not able to create an istance of AppProfile if i write the manual mapping it's working as expected.
_configurationStore.CreateMap<Category, Category>().ReverseMap();

Groovy compiler fails with unexpected token on readObject

My Gradle project has a mix of Java and Groovy classes. All source is under src/main/groovy. One of my Groovy classes contains a Map that I have created from reading a JSON string via JsonSlurper.parseText(). This class is marked Serializable.
To avoid a NotSerializableException, I have implemented my own writeObject() and readObject() methods, but my code is not compiling. I didn't find many Groovy examples, but various Java references and tutorials told me to use these signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException
My class looks like this:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
class GroovyJSONMap implements Serializable {
private static final long serialVersionUID = 20150902L
Map myJSON = [:]
GroovyJSONMap() {
//no op
}
GroovyJSONMap(String json) {
if (json) {
try {
setJSON(json)
} catch (any) {
println "WHOOPS! Not a JSON object...."
myJSON = ["invalid": true]
}
}
}
GroovyJSONMap(Map json) {
if (json) {
setJSON(json)
}
}
final void setJSON(String json) {
myJSON = new JsonSlurper().parseText(json)
}
String getJSON() {
new JsonBuilder(myJSON).toString()
}
#Override
String toString() {
getJSON()
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
setJSON((String)in.readObject())
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(getJSON())
}
}
The compiler error:
:clean
:compileJava UP-TO-DATE
:compileGroovy
startup failed:
c:\path\to\src\main\groovy\GroovyJSONMap.groovy: 44: unexpected token: ObjectInputStream # line 110, column 29.
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
^
1 error
:compileGroovy FAILED
I have moved the readObject() method to various positions in the source, but it still is not compiling. The compiler does not complain about writeObject(), only readObject(). Why is my code not compiling?
The compiler points to ObjectOutputStream, but the problem is really at in.
The word in is a reserved word in Groovy and cannot be used for a variable or method name.
The solution is to rename in to any non-Groovy-reserved word, such as stream (also changed writeObject() for consistency):
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
setJSON((String)stream.readObject())
}
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.writeObject(getJSON())
}

How Test PUT RestController in Spring Boot

How can I test one PUT request with Spring Boot??
I have this method:
#RequestMapping(method = RequestMethod.PUT, value = "/")
public NaturezaTitulo save(#RequestBody NaturezaTitulo naturezaTitulo){
return naturezaTituloService.save(naturezaTitulo);
}
and this test class:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
public class NaturezaTituloControllerTest {
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
private MockMvc mockMvc;
private HttpMessageConverter mappingJackson2HttpMessageConverter;
private List<NaturezaTitulo> naturezaTituloList = new ArrayList<>();
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
void setConverters(HttpMessageConverter<?>[] converters) {
this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter(
hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get();
Assert.assertNotNull("the JSON message converter must not be null",
this.mappingJackson2HttpMessageConverter);
}
#Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
#Test
public void naturezaTituloNotFound() throws Exception {
mockMvc.perform(get("/naturezatitulo/55ce2dd6222e629f4b8d6fe0"))
.andExpect(status().is4xxClientError());
}
#Test
public void naturezaTituloSave() throws Exception {
NaturezaTitulo naturezaTitulo = new NaturezaTitulo();
naturezaTitulo.setNatureza("Testando");
mockMvc.perform(put("/naturezatitulo/").content(this.json(naturezaTitulo))
.contentType(contentType))
.andExpect(jsonPath("$.id", notNullValue()));
}
protected String json(Object o) throws IOException {
MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
this.mappingJackson2HttpMessageConverter.write(
o, MediaType.APPLICATION_JSON, mockHttpOutputMessage);
return mockHttpOutputMessage.getBodyAsString();
}
}
but I got this error:
java.lang.IllegalArgumentException: json can not be null or empty at
com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:259)
how can I pass one object from body in Put test?
tks

Selenium WebDriver, How to run/connect next class

I'm new to Selenium Webdriver, I have a few question :
First, I have 2 class, 'Login.java' and 'SelectCity.java
Class 1 : Login.java
invalidLogin
validLogin
Class 2 : SelectCity.java
For now, in Login.java I wrote
#After
public void tearDown() throws Exception {
driver.close();
}
which mean the browser will closed after finish run right?
Here is my question :
How to make after I run validLogin, it will continue to run the next class (SelectCity.java)?
Is it possible to do that?
How to make last browser (which test valid login) didn't get close?
My current Login.java class :
public class Login extends SelectCityAfterLogin{
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://mysite/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLoginInvalidPass() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("user1");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginInvalidUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("somepassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoPassword() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("myUsername");
driver.findElement(By.id("txtPassword")).sendKeys("password");
driver.findElement(By.id("lbLogin")).click();
Thread.sleep(3000);
}
}
Thx
Yes you can run selectcity after login
You should Extend your First class to Second class
In your Login.java extend it to selectcity java like below
Public class login extends Selectcity {
After your validlogin
create a new instance for selectcity (If you are using #test, create the below in that)
selectcity test = new selectcity()
Once after your valid login do the following
test.(will fetch you the methods available in selectcity.java)
By this way you can call once class to another.
Let me know if this helps
UPDATE :
if selectcityAfterlogin in public class Login extends **SelectCityAfterLogin** is your second class name, then you are creating an incorrect object i guess
In your public login class please check whether your are extending the proper second class name
In #test method
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
it should be
SelectCityAfterLogin selectrole = new SelectCityAfterLogin()
selectrole.(will fetch you the methods of second city)
Please let me know if this helps.
One better solution would be to create multiple methods than multiple #test. You can call these to single #test suite.
I am assuming, you have 2 classes 'Login.java' and 'SelectCity.java'
as follows:
Class 1 : Login.java
public void invalidLogin (WebDriver driver){
//some operations
}
public void validLogin (WebDriver driver){
//some operations
}
Class 2 : SelectCity.java
public void selectCity (Webdriver Driver){
//some operations
}
Class 3: LoginAndSelectCity.java
public static void main(String args []){
WebDriver driver = new FirefoxDriver();
Login.validLogin(driver);
SelectCity.selectCity(driver);
}
If all classes should be in same package then only it works else you need to import packages or create new child to do inheritance of the classes.